code:
<?php
/*
 * StatusNet - the distributed open-source microblogging tool
 * Copyright (C) 2010 StatusNet, Inc.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

define('INSTALLDIR', realpath(dirname(__FILE__) . '/..'));

$shortoptions = 'i:n:f:a:j';
$longoptions = array('id=', 'nickname=', 'file=', 'after=', 'json');

$helptext = <<<END_OF_EXPORTACTIVITYSTREAM_HELP
exportactivitystream.php [options]
Export a StatusNet user history to a file

  -i --id       ID of user to export
  -n --nickname nickname of the user to export
  -j --json     Output JSON (default Atom)
  -a --after    Only activities after the given date

END_OF_EXPORTACTIVITYSTREAM_HELP;

require_once INSTALLDIR.'/scripts/commandline.inc';

try {
    $user = getUser();
    if (have_option('a', 'after')) {
        $afterStr = get_option_value('a', 'after');
        $after = strtotime($afterStr);
        $actstr = new UserActivityStream($user, true, UserActivityStream::OUTPUT_RAW, $after);
    } else {
        $actstr = new UserActivityStream($user, true, UserActivityStream::OUTPUT_RAW);
    }
    if (have_option('j', 'json')) {
        $actstr->writeJSON(STDOUT);
    } else {
        print $actstr->getString();
    }
} catch (Exception $e) {
    print $e->getMessage()."\n";
    exit(1);
}


code:
#!/usr/bin/env php
<?php
/*
 * StatusNet - a distributed open-source microblogging tool
 * Copyright (C) 2008-2011 StatusNet, Inc.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

define('INSTALLDIR', realpath(dirname(__FILE__) . '/..'));

$shortoptions = 'x::';
$longoptions = array('extensions=');

$helptext = <<<END_OF_CHECKSCHEMA_HELP
php checkschema.php [options]
Gives plugins a chance to update the database schema.

    -x --extensions=     Comma-separated list of plugins to load before checking

END_OF_CHECKSCHEMA_HELP;

require_once INSTALLDIR.'/scripts/commandline.inc';

function tableDefs()
{
	$schema = array();
	require INSTALLDIR.'/db/core.php';
	return $schema;
}

$schema = Schema::get();
$schemaUpdater = new SchemaUpdater($schema);
foreach (tableDefs() as $table => $def) {
	$schemaUpdater->register($table, $def);
}
$schemaUpdater->checkSchema();

if (have_option('x', 'extensions')) {
    $ext = trim(get_option_value('x', 'extensions'));
    $exts = explode(',', $ext);
    foreach ($exts as $plugin) {
        try {
            addPlugin($plugin);
        } catch (Exception $e) {
            print $e->getMessage()."\n";
            exit(1);
        }
    }
}

Event::handle('BeforePluginCheckSchema');
Event::handle('CheckSchema');

repo_name: RMichael/gnu

license: mit


code:
#!/usr/bin/env php
<?php
/*
 * StatusNet - a distributed open-source microblogging tool
 * Copyright (C) 2008, 2009, StatusNet, Inc.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

define('INSTALLDIR', realpath(dirname(__FILE__) . '/..'));

$shortoptions = 'y';
$longoptions = array('yes');

$helptext = <<<END_OF_HELP
clean_file_table.php [options]
Deletes all local files where the filename cannot be found in the filesystem.

  -y --yes      do not wait for confirmation

Will print '.' for each file, except for deleted ones which are marked as 'x'.

END_OF_HELP;

require_once INSTALLDIR.'/scripts/commandline.inc';

if (!have_option('y', 'yes')) {
    print "About to delete local file entries where the file cannot be found. Are you sure? [y/N] ";
    $response = fgets(STDIN);
    if (strtolower(trim($response)) != 'y') {
        print "Aborting.\n";
        exit(0);
    }
}

print "Deleting";
$file = new File();
$file->whereAdd('filename IS NOT NULL');        // local files
$file->whereAdd('filehash IS NULL', 'AND');     // without filehash value
if ($file->find()) {
    while ($file->fetch()) {
        try {
            $file->getPath();
            print '.';
        } catch (FileNotFoundException $e) {
            $file->delete();
            print 'x';
        }
    }
}
print "\nDONE.\n";


code:
#!/usr/bin/env php
<?php
/*
 * StatusNet - a distributed open-source microblogging tool
 * Copyright (C) 2008, 2009, StatusNet, Inc.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

define('INSTALLDIR', realpath(dirname(__FILE__) . '/..'));

$shortoptions = 'y';
$longoptions = array('yes');

$helptext = <<<END_OF_HELP
clean_profiles.php [options]
Deletes all profile table entries where the profile does not occur in the
notice table, is not a group and is not a local user. Very MySQL specific I think.

WARNING: This has not been tested thoroughly. Maybe we've missed a table to compare somewhere.

  -y --yes      do not wait for confirmation

END_OF_HELP;

require_once INSTALLDIR.'/scripts/commandline.inc';

if (!have_option('y', 'yes')) {
    print "About to delete profiles that we think are useless to save. Are you sure? [y/N] ";
    $response = fgets(STDIN);
    if (strtolower(trim($response)) != 'y') {
        print "Aborting.\n";
        exit(0);
    }
}

print "Deleting";
$profile = new Profile();
$profile->query('SELECT * FROM profile WHERE ' .
                'NOT (SELECT COUNT(*) FROM notice WHERE profile_id=profile.id) ' .
                'AND NOT (SELECT COUNT(*) FROM user WHERE user.id=profile.id) ' .
                'AND NOT (SELECT COUNT(*) FROM user_group WHERE user_group.profile_id=profile.id) ' .
                'AND NOT (SELECT COUNT(*) FROM subscription WHERE subscriber=profile.id OR subscribed=profile.id) ');
while ($profile->fetch()) {
    echo ' '.$profile->getID().':'.$profile->getNickname();
    $profile->delete();
}
print "\nDONE.\n";


code:
#!/usr/bin/env php
<?php
/*
 * StatusNet - a distributed open-source microblogging tool
 * Copyright (C) 2008, 2009, StatusNet, Inc.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

define('INSTALLDIR', realpath(dirname(__FILE__) . '/..'));

$shortoptions = 'y';
$longoptions = array('yes');

$helptext = <<<END_OF_HELP
clean_thumbnails.php [options]
Deletes all local thumbnails so they can be regenerated. Also deletes
if the original File object does not exist, even for remote entries.

  -y --yes      do not wait for confirmation

Will print '.' for deleted local files and 'x' where File entry was missing.
If the script seems to stop, it is processing correct File_thumbnail entries.

END_OF_HELP;

require_once INSTALLDIR.'/scripts/commandline.inc';

if (!have_option('y', 'yes')) {
    print "About to delete locally generated thumbnails to allow regeneration. Are you sure? [y/N] ";
    $response = fgets(STDIN);
    if (strtolower(trim($response)) != 'y') {
        print "Aborting.\n";
        exit(0);
    }
}

print "Deleting";
$thumbs = new File_thumbnail();
$thumbs->find();
while ($thumbs->fetch()) {
    try {
        $file = $thumbs->getFile();
        if ($file->isLocal()) {
            // only delete properly linked thumbnails if they're local
            $thumbs->delete();
            print '.';
        }
    } catch (NoResultException $e) {
        // No File object for thumbnail, let's delete the thumbnail entry
        $thumbs->delete();
        print 'x';
    }
}
print "\nDONE.\n";


code:
#!/usr/bin/env php
<?php
/*
 * StatusNet - a distributed open-source microblogging tool
 * Copyright (C) 2008, 2009, 2010, StatusNet, Inc.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

define('INSTALLDIR', realpath(dirname(__FILE__) . '/..'));

$shortoptions = 'i::n::y';
$longoptions = array('id=', 'nickname=', 'yes', 'all', 'dry-run');

$helptext = <<<END_OF_DELETEUSER_HELP
clear_jabber.php [options]
Deletes a user's confirmed Jabber/XMPP address from the database.

  -i --id       ID of the user
  -n --nickname nickname of the user
     --all      all users with confirmed Jabber addresses
     --dry-run  Don't actually delete info.

END_OF_DELETEUSER_HELP;

require_once INSTALLDIR.'/scripts/commandline.inc';

if (have_option('i', 'id')) {
    $id = get_option_value('i', 'id');
    $user = User::getKV('id', $id);
    if (empty($user)) {
        print "Can't find user with ID $id\n";
        exit(1);
    }
} else if (have_option('n', 'nickname')) {
    $nickname = get_option_value('n', 'nickname');
    $user = User::getKV('nickname', $nickname);
    if (empty($user)) {
        print "Can't find user with nickname '$nickname'\n";
        exit(1);
    }
} else if (have_option('all')) {
    $user = new User();
    $user->whereAdd("jabber != ''");
    $user->find(true);
    if ($user->N == 0) {
        print "No users with registered Jabber addresses in database.\n";
        exit(1);
    }
} else {
    print "You must provide either an ID or a nickname.\n";
    print "\n";
    print $helptext;
    exit(1);
}

function clear_jabber($id)
{
    $user = User::getKV('id', $id);
    if ($user && $user->jabber) {
        echo "clearing user $id's user.jabber, was: $user->jabber";
        if (have_option('dry-run')) {
            echo " (SKIPPING)";
        } else {
            $original = clone($user);
            $user->jabber = null;
            try {
                $user->updateWithKeys($original);
            } catch (Exception $e) {
                echo "WARNING: user update failed (setting jabber to null): ".$e->getMessage()."\n";
            }
        }
        echo "\n";
    } else if (!$user) {
        echo "Missing user for $id\n";
    } else {
        echo "Cleared jabber already for $id\n";
    }
}

do {
    clear_jabber($user->id);
} while ($user->fetch());

print "DONE.\n";


code:
#!/usr/bin/env php
<?php
/*
 * StatusNet - the distributed open-source microblogging tool
 * Copyright (C) 2009, StatusNet, Inc.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

define('INSTALLDIR', realpath(dirname(__FILE__) . '/..'));

$shortoptions = "t:l:v:k:";

$helptext = <<<END_OF_CLEARCACHE_HELP
USAGE: clearcache.php <args>
clears the cached object based on the args

  -t table     Table to look up
  -l column    Column to look up, default "id"
  -v value     Value to look up
  -k key       Key to look up; other args are ignored

END_OF_CLEARCACHE_HELP;

require_once INSTALLDIR.'/scripts/commandline.inc';

$karg = get_option_value('k', 'key');

if (!empty($karg)) {
    $k = Cache::key($karg);
} else {
    $table = get_option_value('t', 'table');
    if (empty($table)) {
        die("No table or key specified\n");
    }
    $column = get_option_value('l', 'column');
    if (empty($column)) {
        $column = 'id';
    }
    $value = get_option_value('v', 'value');

    $k = Memcached_DataObject::cacheKey($table, $column, $value);
}

print "Clearing key '$k'...";

$c = Cache::instance();

if (empty($c)) {
    die("Can't initialize cache object!\n");
}

$result = $c->delete($k);

if ($result) {
    print "OK.\n";
} else {
    print "FAIL.\n";
}


code:
#!/usr/bin/env php
<?php
/*
 * StatusNet - a distributed open-source microblogging tool
 * Copyright (C) 2008, 2009, 2010 StatusNet, Inc.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

define('INSTALLDIR', realpath(dirname(__FILE__) . '/..'));

$shortoptions = 'i:n:o';
$longoptions = array('id=', 'nickname=', 'owner');

$helptext = <<<END_OF_USERROLE_HELP
command.php [options] [command line]
Perform commands on behalf of a user, such as sub, unsub, join, drop

  -i --id       ID of the user
  -n --nickname nickname of the user
  -o --owner    use the site owner

END_OF_USERROLE_HELP;

require_once INSTALLDIR.'/scripts/commandline.inc';

function interpretCommand($user, $body)
{
    $inter = new CommandInterpreter();
    $chan = new CLIChannel();
    $cmd = $inter->handle_command($user, $body);
    if ($cmd) {
        $cmd->execute($chan);
        return true;
    } else {
        $chan->error($user, "Not a valid command. Try 'help'?");
        return false;
    }
}

if (have_option('i', 'id')) {
    $id = get_option_value('i', 'id');
    $user = User::getKV('id', $id);
    if (empty($user)) {
        print "Can't find user with ID $id\n";
        exit(1);
    }
} else if (have_option('n', 'nickname')) {
    $nickname = get_option_value('n', 'nickname');
    $user = User::getKV('nickname', $nickname);
    if (empty($user)) {
        print "Can't find user with nickname '$nickname'\n";
        exit(1);
    }
} else if (have_option('o', 'owner')) {
    try {
        $user = User::siteOwner();
    } catch (ServerException $e) {
        print "Site has no owner.\n";
        exit(1);
    }
} else {
    print "You must provide either an ID or a nickname.\n\n";
    print $helptext;
    exit(1);
}

// @todo refactor the interactive console in console.php and use
// that to optionally make an interactive test console here too.
// Would be good to help people test commands when XMPP or email
// isn't available locally.
interpretCommand($user, implode(' ', $args));


code:
<?php
/*
 * StatusNet - a distributed open-source microblogging tool
 * Copyright (C) 2008, 2009, StatusNet, Inc.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

// -*- mode: php -*-

# Abort if called from a web server

if (isset($_SERVER) && array_key_exists('REQUEST_METHOD', $_SERVER)) {
    print "This script must be run from the command line\n";
    exit();
}

define('GNUSOCIAL', true);
define('STATUSNET', true); //compatibility

define('GNUSOCIAL_CLI', true);  // to know we're in a CLI environment

// Set various flags so we don't time out on long-running processes

ini_set("max_execution_time", "0");
ini_set("max_input_time", "0");
set_time_limit(0);
mb_internal_encoding('UTF-8');
error_reporting(E_ALL & ~E_STRICT & ~E_DEPRECATED);

// Add extlib to our path so we can get Console_Getopt

$_extra_path = array(INSTALLDIR.'/extlib/');

set_include_path(implode(PATH_SEPARATOR, $_extra_path) . PATH_SEPARATOR . get_include_path());

require_once 'Console/Getopt.php';

// Note: $shortoptions and $longoptions should be pre-defined!

$_default_shortoptions = 'qvhc:s:p:';

$_default_longoptions = array('quiet', 'verbose', 'help', 'conf=', 'server=', 'path=');

if (isset($shortoptions)) {
    $shortoptions .= $_default_shortoptions;
} else {
    $shortoptions = $_default_shortoptions;
}

if (isset($longoptions)) {
    $longoptions = array_merge($longoptions, $_default_longoptions);
} else {
    $longoptions = $_default_longoptions;
}

$parser = new Console_Getopt();

$result = $parser->getopt($argv, $shortoptions, $longoptions);

if (PEAR::isError($result)) {
    print $result->getMessage()."\n";
    exit(1);
} else {
    list($options, $args) = $result;
}

function show_help()
{
    global $helptext;

    $_default_help_text = <<<END_OF_DEFAULT
      General options:

    -q --quiet           Quiet (little output)
    -v --verbose         Verbose (lots of output)
    -c --conf=<filename> Use <filename> as config file
    -s --server=<name>   Use <name> as server name
    -p --path=<path>     Use <path> as path name
    -h --help            Show this message and quit.

END_OF_DEFAULT;
    if (isset($helptext)) {
        print $helptext;
    }
    print $_default_help_text;
    exit(0);
}

foreach ($options as $option) {

    switch ($option[0]) {
     case '--server':
     case 's':
        $server = $option[1];
        break;

     case '--path':
     case 'p':
        $path = $option[1];
        break;

     case '--conf':
     case 'c':
        $conffile = $option[1];
        break;

     case '--help':
     case 'h':
        show_help();
    }
}

require_once INSTALLDIR . '/lib/common.php';

set_error_handler('common_error_handler');

// Set up the language infrastructure so we can localize anything that
// needs to be sent out to users, such as mail notifications.
common_init_language();

function _make_matches($opt, $alt)
{
    $matches = array();

    if (strlen($opt) > 1 && 0 != strncmp($opt, '--', 2)) {
        $matches[] = '--'.$opt;
    } else {
        $matches[] = $opt;
    }

    if (!empty($alt)) {
        if (strlen($alt) > 1 && 0 != strncmp($alt, '--', 2)) {
            $matches[] = '--'.$alt;
        } else {
            $matches[] = $alt;
        }
    }

    return $matches;
}

function have_option($opt, $alt=null)
{
    global $options;

    $matches = _make_matches($opt, $alt);

    foreach ($options as $option) {
        if (in_array($option[0], $matches)) {
            return true;
        }
    }

    return false;
}

function get_option_value($opt, $alt=null)
{
    global $options;

    $matches = _make_matches($opt, $alt);

    foreach ($options as $option) {
        if (in_array($option[0], $matches)) {
            return $option[1];
        }
    }

    return null;
}

class NoUserArgumentException extends Exception
{
}

function getUser()
{
    $user = null;

    if (have_option('i', 'id')) {
        $id = get_option_value('i', 'id');
        $user = User::getKV('id', $id);
        if (empty($user)) {
            throw new Exception("Can't find user with id '$id'.");
        }
    } else if (have_option('n', 'nickname')) {
        $nickname = get_option_value('n', 'nickname');
        $user = User::getKV('nickname', $nickname);
        if (empty($user)) {
            throw new Exception("Can't find user with nickname '$nickname'");
        }
    } else {
        throw new NoUserArgumentException("No user argument specified.");
    }

    return $user;
}

/** "Printf not quiet" */

function printfnq()
{
    if (have_option('q', 'quiet')) {
        return null;
    }

    $cargs  = func_num_args();

    if ($cargs == 0) {
        return 0;
    }

    $args   = func_get_args();
    $format = array_shift($args);

    return vprintf($format, $args);
}

/** "Print when verbose" */

function printfv()
{
    if (!have_option('v', 'verbose')) {
        return null;
    }

    $cargs  = func_num_args();

    if ($cargs == 0) {
        return 0;
    }

    $args   = func_get_args();
    $format = array_shift($args);

    return vprintf($format, $args);
}


code:
#!/usr/bin/env php
<?php
/*
 * StatusNet - the distributed open-source microblogging tool
 * Copyright (C) 2009, StatusNet, Inc.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

// Abort if called from a web server

define('INSTALLDIR', realpath(dirname(__FILE__) . '/..'));

$helptext = <<<ENDOFHELP
console.php - provide an interactive PHP interpreter for testing

ENDOFHELP;

require_once INSTALLDIR.'/scripts/commandline.inc';

// Assume we're on a terminal if on Windows, otherwise posix_isatty tells us.
define('CONSOLE_INTERACTIVE', !function_exists('posix_isatty') || posix_isatty(0));
define('CONSOLE_READLINE', CONSOLE_INTERACTIVE && function_exists('readline'));

if (CONSOLE_READLINE && CONSOLE_INTERACTIVE) {
    define('CONSOLE_HISTORY', getenv("HOME") . "/.statusnet_console_history");
    if (file_exists(CONSOLE_HISTORY)) {
        readline_read_history(CONSOLE_HISTORY);
    }
}

function read_input_line($prompt)
{
    if (CONSOLE_INTERACTIVE) {
        if (CONSOLE_READLINE) {
            $line = readline($prompt);
            if (trim($line) != '') {
                readline_add_history($line);
                if (defined('CONSOLE_HISTORY')) {
                    // Save often; it's easy to hit fatal errors.
                    readline_write_history(CONSOLE_HISTORY);
                }
            }
            return $line;
        } else {
            return readline_emulation($prompt);
        }
    } else {
        return fgets(STDIN);
    }
}

/**
 * On Unix-like systems where PHP readline extension isn't present,
 * -cough- Mac OS X -cough- we can shell out to bash to do it for us.
 * This lets us at least handle things like arrow keys, but we don't
 * get any entry history. :(
 *
 * Shamelessly ripped from when I wrote the same code for MediaWiki. :)
 * @author Brion Vibber <brion@status.net>
 *
 * @param string $prompt
 * @return mixed string on success, false on fail or EOF
 */
function readline_emulation($prompt)
{
    if(CONSOLE_INTERACTIVE && file_exists(trim(shell_exec('which bash')))) {
        $encPrompt = escapeshellarg($prompt);
        $command = "read -er -p $encPrompt && echo \"\$REPLY\"";
        $encCommand = escapeshellarg($command);
        $metaCommand = "bash -c $encCommand";

        // passthru passes our STDIN and TTY to the child...
        // We can pull the returned string via output buffering.
        ob_start();
        $retval = false;
        passthru($metaCommand, $retval);
        $line = ob_get_contents();
        ob_end_clean();

        if ($retval == 0) {
            return $line;
        } elseif ($retval == 127) {
            // Couldn't execute bash even though we thought we saw it.
            // Shell probably spit out an error message, sorry :(
            // Fall through to fgets()...
        } else {
            // EOF/ctrl+D
            return false;
        }
    }

    // Fallback... we'll have no editing controls, EWWW
    if (feof(STDIN)) {
        return false;
    }
    if (CONSOLE_INTERACTIVE) {
        print $prompt;
    }
    return fgets(STDIN);
}

function console_help()
{
    print "Welcome to GNU social's interactive PHP console!\n";
    print "Type some PHP code and it'll execute...\n";
    print "\n";
    print "Hint: return a value of any type to output it via var_export():\n";
    print "  \$profile = new Profile();\n";
    print "  \$profile->find();\n";
    print "  \$profile->fetch();\n";
    print "  return \$profile;\n";
    print "\n";
    print "Note that PHP is cranky and you can easily kill your session by mistyping.\n";
    print "\n";
    print "Type ctrl+D or enter 'exit' to exit.\n";
}

if (CONSOLE_INTERACTIVE) {
    print "GNU social interactive PHP console... type ctrl+D or enter 'exit' to exit.\n";
    $prompt = common_slugify(common_config('site', 'name')) . '> ';
} else {
    $prompt = '';
}
while (!feof(STDIN)) {
    $line = read_input_line($prompt);
    if ($line === false) {
        if (CONSOLE_INTERACTIVE) {
            print "\n";
        }
        break;
    } elseif ($line !== '') {
        try {
            if (trim($line) == 'exit') {
                break;
            } elseif (trim($line) == 'help') {
                console_help();
                continue;
            }

            // Let's do this!
            $result = eval($line);
            if ($result === false) {
                // parse error
            } elseif ($result === null) {
                // no return
            } else {
                // return value from eval'd code
                var_export($result);
            }
        } catch(Exception $e) {
            print get_class($e) . ": " . $e->getMessage() . "\n";
        }
    }
    if (CONSOLE_INTERACTIVE) {
        print "\n";
    }
}


code:
#!/usr/bin/env php
<?php
/*
 * StatusNet - the distributed open-source microblogging tool
 * Copyright (C) 2008, 2009, StatusNet, Inc.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

define('INSTALLDIR', realpath(dirname(__FILE__) . '/..'));

$shortoptions = 'b:g:j:n:t:u:w:x:z:';
$longoptions = array(
    'subscriptions=',
    'groups=',
    'joins=',
    'notices=',
    'tags=',
    'users=',
    'words=',
    'prefix=',
    'groupprefix=',
//    'faves=',
);

$helptext = <<<END_OF_CREATESIM_HELP
Creates a lot of test users and notices to (loosely) simulate a real server.

    -b --subscriptions Average subscriptions per user (default no. users/20)
    -g --groups        Number of groups (default 20)
    -j --joins         Number of groups per user (default 5)
    -n --notices       Average notices per user (default 100)
    -t --tags          Number of distinct hash tags (default 10000)
    -u --users         Number of users (default 100)
    -w --words         Words file (default '/usr/share/dict/words')
    -x --prefix        User name prefix (default 'testuser')
    -z --groupprefix   Group name prefix (default 'testgroup')

END_OF_CREATESIM_HELP;

require_once INSTALLDIR.'/scripts/commandline.inc';

// XXX: make these command-line options

function newUser($i)
{
    global $userprefix;
    $user = User::register(array('nickname' => sprintf('%s%d', $userprefix, $i),
                                 'password' => sprintf('password%d', $i),
                                 'fullname' => sprintf('Test User %d', $i)));
    if (!empty($user)) {
        $user->free();
    }
}

function newGroup($i, $j)
{
    global $groupprefix;
    global $userprefix;

    // Pick a random user to be the admin

    $n = rand(0, max($j - 1, 0));
    $user = User::getKV('nickname', sprintf('%s%d', $userprefix, $n));

    $group = User_group::register(array('nickname' => sprintf('%s%d', $groupprefix, $i),
                                        'local'    => true,
                                        'userid'   => $user->id,
                                        'fullname' => sprintf('Test Group %d', $i)));
}

function newNotice($i, $tagmax)
{
    global $userprefix;

    $options = array('scope' => Notice::defaultScope());

    $n = rand(0, $i - 1);
    $user = User::getKV('nickname', sprintf('%s%d', $userprefix, $n));

    $is_reply = rand(0, 1);

    $content = testNoticeContent();

    if ($is_reply == 0) {
        $stream = new InboxNoticeStream($user->getProfile(), $user->getProfile());
        $notices = $stream->getNotices(0, 20);
        if ($notices->N > 0) {
            $nval = rand(0, $notices->N - 1);
            $notices->fetch(); // go to 0th
            for ($i = 0; $i < $nval; $i++) {
                $notices->fetch();
            }
            $options['reply_to'] = $notices->id;
            $dont_use_nickname = rand(0, 2);
            if ($dont_use_nickname != 0) {
                $rprofile = $notices->getProfile();
                $content = "@".$rprofile->nickname." ".$content;
            }
            $private_to_addressees = rand(0, 4);
            if ($private_to_addressees == 0) {
                $options['scope'] |= Notice::ADDRESSEE_SCOPE;
            }
        }
    } else {
        $is_directed = rand(0, 4);

        if ($is_directed == 0) {
            $subs = $user->getSubscribed(0, 100)->fetchAll();
            if (count($subs) > 0) {
                $seen = array();
                $f = rand(0, 9);
                if ($f <= 6) {
                    $addrs = 1;
                } else if ($f <= 8) {
                    $addrs = 2;
                } else {
                    $addrs = 3;
                }
                for ($m = 0; $m < $addrs; $m++) {
                    $x = rand(0, count($subs) - 1);
                    if ($seen[$x]) {
                        continue;
                    }
                    if ($subs[$x]->id == $user->id) {
                        continue;
                    }
                    $seen[$x] = true;
                    $rprofile = $subs[$x];
                    $content = "@".$rprofile->nickname." ".$content;
                }
                $private_to_addressees = rand(0, 4);
                if ($private_to_addressees == 0) {
                    $options['scope'] |= Notice::ADDRESSEE_SCOPE;
                }
            }
        }
    }

    $has_hash = rand(0, 2);

    if ($has_hash == 0) {
        $hashcount = rand(0, 2);
        for ($j = 0; $j < $hashcount; $j++) {
            $h = rand(0, $tagmax);
            $content .= " #tag{$h}";
        }
    }

    $in_group = rand(0, 5);

    if ($in_group == 0) {
        $groups = $user->getGroups();
        if ($groups instanceof User_group) {
            $gval = rand(0, $groups->N - 1);
            $groups->fetch(); // go to 0th
            for ($i = 0; $i < $gval; $i++) {
                $groups->fetch();
            }
            $options['groups'] = array($groups->id);
            $content = "!".$groups->nickname." ".$content;
            $private_to_group = rand(0, 2);
            if ($private_to_group == 0) {
                $options['scope'] |= Notice::GROUP_SCOPE;
            }
        }
    }

    $private_to_site = rand(0, 4);

    if ($private_to_site == 0) {
        $options['scope'] |= Notice::SITE_SCOPE;
    }

    $notice = Notice::saveNew($user->id, $content, 'createsim', $options);
}

/* Plugins should be part of the simulation too!
function newMessage($i)
{
    global $userprefix;

    $n = rand(0, $i - 1);
    $user = User::getKV('nickname', sprintf('%s%d', $userprefix, $n));

    $content = testNoticeContent();

    $friends = $user->mutuallySubscribedUsers()->fetchAll();

    if (count($friends) == 0) {
        return;
    }

    $j = rand(0, count($friends) - 1);

    $other = $friends[$j];

    $message = Message::saveNew($user->id, $other->id, $content, 'createsim');
}*/

function newSub($i)
{
    global $userprefix;
    $f = rand(0, $i - 1);

    $fromnick = sprintf('%s%d', $userprefix, $f);

    $from = User::getKV('nickname', $fromnick);

    if (empty($from)) {
        throw new Exception("Can't find user '$fromnick'.");
    }

    $t = rand(0, $i - 1);

    if ($t == $f) {
        $t++;
        if ($t > $i - 1) {
            $t = 0;
        }
    }

    $tunic = sprintf('%s%d', $userprefix, $t);

    $to = User::getKV('nickname', $tunic);

    if (!($to instanceof User)) {
        throw new Exception("Can't find user '$tunic'.");
    }

    Subscription::start($from->getProfile(), $to->getProfile());

    $from->free();
    $to->free();
}

function newJoin($u, $g)
{
    global $userprefix;
    global $groupprefix;

    $userNumber = rand(0, $u - 1);

    $userNick = sprintf('%s%d', $userprefix, $userNumber);

    $user = User::getKV('nickname', $userNick);

    if (empty($user)) {
        throw new Exception("Can't find user '$fromnick'.");
    }

    $groupNumber = rand(0, $g - 1);

    $groupNick = sprintf('%s%d', $groupprefix, $groupNumber);

    $group = User_group::getKV('nickname', $groupNick);

    if (empty($group)) {
        throw new Exception("Can't find group '$groupNick'.");
    }

    if (!$user->isMember($group)) {
        $user->joinGroup($group);
    }
}

/* Plugins should be part of the simulation too!
function newFave($u)
{
    global $userprefix;
    global $groupprefix;

    $userNumber = rand(0, $u - 1);

    $userNick = sprintf('%s%d', $userprefix, $userNumber);

    $user = User::getKV('nickname', $userNick);

    if (empty($user)) {
        throw new Exception("Can't find user '$userNick'.");
    }

    // NB: it's OK to like your own stuff!

    $otherNumber = rand(0, $u - 1);

    $otherNick = sprintf('%s%d', $userprefix, $otherNumber);

    $other = User::getKV('nickname', $otherNick);

    if (empty($other)) {
        throw new Exception("Can't find user '$otherNick'.");
    }

    $notices = $other->getNotices()->fetchAll();

    if (count($notices) == 0) {
        return;
    }

    $idx = rand(0, count($notices) - 1);

    $notice = $notices[$idx];

    if ($user->hasFave($notice)) {
        return;
    }

    Fave::addNew($user->getProfile(), $notice);
}*/

function testNoticeContent()
{
    global $words;

    if (is_null($words)) {
        return "test notice content";
    }

    $cnt = rand(3, 8);

    $ids = array_rand($words, $cnt);

    foreach ($ids as $id) {
        $parts[] = $words[$id];
    }

    $text = implode(' ', $parts);

    if (mb_strlen($text) > 80) {
        $text = substr($text, 0, 77) . "...";
    }

    return $text;
}

//function main($usercount, $groupcount, $noticeavg, $subsavg, $joinsavg, $favesavg, $messageavg, $tagmax)
function main($usercount, $groupcount, $noticeavg, $subsavg, $joinsavg, $tagmax)
{
    global $config;
    $config['site']['dupelimit'] = -1;

    $n = 0;
    $g = 0;

    // Make users first

    $preuser = min($usercount, 5);

    for ($j = 0; $j < $preuser; $j++) {
        printfv("$i Creating user $n\n");
        newUser($n);
        $n++;
    }

    $pregroup = min($groupcount, 3);

    for ($k = 0; $k < $pregroup; $k++) {
        printfv("$i Creating group $g\n");
        newGroup($g, $n);
        $g++;
    }

    // # registrations + # notices + # subs

    //$events = $usercount + $groupcount + ($usercount * ($noticeavg + $subsavg + $joinsavg + $favesavg + $messageavg));
    $events = $usercount + $groupcount + ($usercount * ($noticeavg + $subsavg + $joinsavg));

    $events -= $preuser;
    $events -= $pregroup;

    $ut = $usercount;
    $gt = $ut + $groupcount;
    $nt = $gt + ($usercount * $noticeavg);
    $st = $nt + ($usercount * $subsavg);
    $jt = $st + ($usercount * $joinsavg);
//    $ft = $jt + ($usercount * $favesavg);
//    $mt = $ft + ($usercount * $messageavg);

//    printfv("$events events ($ut, $gt, $nt, $st, $jt, $ft, $mt)\n");
    printfv("$events events ($ut, $gt, $nt, $st, $jt)\n");

    for ($i = 0; $i < $events; $i++)
    {
        $e = rand(0, $events);

        if ($e >= 0 && $e <= $ut) {
            printfv("$i Creating user $n\n");
            newUser($n);
            $n++;
        } else if ($e > $ut && $e <= $gt) {
            printfv("$i Creating group $g\n");
            newGroup($g, $n);
            $g++;
        } else if ($e > $gt && $e <= $nt) {
            printfv("$i Making a new notice\n");
            newNotice($n, $tagmax);
        } else if ($e > $nt && $e <= $st) {
            printfv("$i Making a new subscription\n");
            newSub($n);
        } else if ($e > $st && $e <= $jt) {
            printfv("$i Making a new group join\n");
            newJoin($n, $g);
/*        } else if ($e > $jt && $e <= $ft) {
            printfv("$i Making a new fave\n");
            newFave($n);*/
/*        } else if ($e > $ft && $e <= $mt) {
            printfv("$i Making a new message\n");
            newMessage($n);*/
        } else {
            printfv("No event for $i!");
        }
    }
}

$defaultWordsfile = '/usr/share/dict/words';

$usercount   = (have_option('u', 'users')) ? get_option_value('u', 'users') : 100;
$groupcount  = (have_option('g', 'groups')) ? get_option_value('g', 'groups') : 20;
$noticeavg   = (have_option('n', 'notices')) ? get_option_value('n', 'notices') : 100;
$subsavg     = (have_option('b', 'subscriptions')) ? get_option_value('b', 'subscriptions') : max($usercount/20, 10);
$joinsavg    = (have_option('j', 'joins')) ? get_option_value('j', 'joins') : 5;
//$favesavg    = (have_option('f', 'faves')) ? get_option_value('f', 'faves') : max($noticeavg/10, 5);
//$messageavg  = (have_option('m', 'messages')) ? get_option_value('m', 'messages') : max($noticeavg/10, 5);
$tagmax      = (have_option('t', 'tags')) ? get_option_value('t', 'tags') : 10000;
$userprefix  = (have_option('x', 'prefix')) ? get_option_value('x', 'prefix') : 'testuser';
$groupprefix = (have_option('z', 'groupprefix')) ? get_option_value('z', 'groupprefix') : 'testgroup';
$wordsfile   = (have_option('w', 'words')) ? get_option_value('w', 'words') : $defaultWordsfile;

if (is_readable($wordsfile)) {
    $words = file($wordsfile);
} else {
   if ($wordsfile != $defaultWordsfile) {
      // user specified words file couldn't be read
      throw new Exception("Couldn't read words file: {$wordsfile}.");
    }
    $words = null;
}

try {
    //main($usercount, $groupcount, $noticeavg, $subsavg, $joinsavg, $favesavg, $messageavg, $tagmax);
    main($usercount, $groupcount, $noticeavg, $subsavg, $joinsavg, $tagmax);
} catch (Exception $e) {
    printfv("Got an exception: ".$e->getMessage());
}


code:
#!/usr/bin/env php
<?php
/*
 * StatusNet - a distributed open-source microblogging tool
 * Copyright (C) 2008, 2009, StatusNet, Inc.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

define('INSTALLDIR', realpath(dirname(__FILE__) . '/..'));

$shortoptions = 'i::u::y';
$longoptions = array('id=', 'uri=', 'yes');

$helptext = <<<END_OF_HELP
delete_notice.php [options]
deletes a notice (but not related File objects) from the database

  -i --id       Local ID of the notice
  -u --uri      Notice URI
  -y --yes      do not wait for confirmation

END_OF_HELP;

require_once INSTALLDIR.'/scripts/commandline.inc';

try {
    if (have_option('i', 'id')) {
        $id = get_option_value('i', 'id');
        $notice = Notice::getByID($id);
    } else if (have_option('u', 'uri')) {
        $uri = get_option_value('u', 'uri');
        $notice = Notice::getByUri($uri);
    } else {
        print $helptext;
        throw new ClientException('You must provide either an ID or a URI.');
    }
} catch (Exception $e) {
    print "ERROR: {$e->getMessage()}\n";
    exit(1);
}

if (!have_option('y', 'yes')) {
    print "About to PERMANENTLY delete notice ".$notice->getID()." by '".$notice->getProfile()->getNickname()."'. Are you sure? [y/N] ";
    $response = fgets(STDIN);
    if (strtolower(trim($response)) != 'y') {
        print "Aborting.\n";
        exit(0);
    }
}

print "Deleting...";
$notice->delete();
print "DONE.\n";


code:
#!/usr/bin/env php
<?php
/*
 * StatusNet - a distributed open-source microblogging tool
 * Copyright (C) 2008, 2009, StatusNet, Inc.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

define('INSTALLDIR', realpath(dirname(__FILE__) . '/..'));

$shortoptions = 'y';
$longoptions = array('yes');

$helptext = <<<END_OF_HELP
delete_orphan_files.php [options]
Deletes all files and their File entries where there is no link to a
Notice entry. Good for cleaning up after user deletion or so where the
attached files weren't removed as well.

  -y --yes      do not wait for confirmation

Will print '.' for each deleted File entry and 'x' if it also had a locally stored file.

WARNING WARNING WARNING, this will also delete Qvitter files such as background etc. since
they are not linked to notices (yet anyway).

END_OF_HELP;

require_once INSTALLDIR.'/scripts/commandline.inc';

print "Finding File entries that are not related to a Notice (or the notice has been deleted)...";
$file = new File();
$sql = 'SELECT file.* FROM file'.
        ' LEFT JOIN file_to_post ON file_to_post.file_id=file.id'.
        ' WHERE'.
            ' NOT EXISTS (SELECT file_to_post.file_id FROM file_to_post WHERE file.id=file_to_post.file_id)'.
            ' OR NOT EXISTS (SELECT notice.id FROM notice WHERE notice.id=file_to_post.post_id)'.
            ' GROUP BY file.id;';

if ($file->query($sql) !== false) {
    print " {$file->N} found.\n";
    if ($file->N == 0) {
        exit(0);
    }
} else {
    print "FAILED";
    exit(1);
}

if (!have_option('y', 'yes')) {
    print "About to delete the entries along with locally stored files. Are you sure? [y/N] ";
    $response = fgets(STDIN);
    if (strtolower(trim($response)) != 'y') {
        print "Aborting.\n";
        exit(0);
    }
}

print "\nDeleting: ";
while ($file->fetch()) {
    try {
        $file->getPath();
        $file->delete();
        print 'x';
    } catch (Exception $e) {
        // either FileNotFound exception or ClientException
        $file->delete();
        print '.';
    }
}
print "\nDONE.\n";


code:
#!/bin/bash

# live fast! die young!

set -e

source /etc/statusnet/setup.cfg || (echo "Failed to read /etc/statusnet/setup.cfg"; exit -1)

export nickname=$1
if [ "x" == "x$nickname" ]
then
    echo "Usage: delete_status_network.sh <site-nickname>"
    exit 1
fi

export database=$nickname$DBBASE

# Pull the status_network record so we know which DB server to drop from...
TARGET_DBHOST=`mysql -h $DBHOST -u $ADMIN --password=$ADMINPASS $SITEDB --batch --skip-column-names -e \
  "select dbhost from status_network where nickname='$nickname'"`

if [ "x" == "x$TARGET_DBHOST" ]
then
    echo "Aborting: Could not find status_network record for site $nickname"
    exit 1
fi

# Drop the database
echo "Dropping $database from $TARGET_DBHOST..."
mysqladmin -h $TARGET_DBHOST -u $ADMIN --password=$ADMINPASS -f drop $database || exit 1

# Remove the status_network entry
echo "Removing status_network entry for $nickname..."
mysql -h $DBHOST -u $ADMIN --password=$ADMINPASS $SITEDB -e \
    "delete from status_network where nickname = '$nickname'" || exit 1

# Remove uploaded file areas
for top in $AVATARBASE $FILEBASE $BACKGROUNDBASE; do
    if [ "x" == "x$top" ]
    then
        echo "Skipping deletion due to broken config"
    else
        echo "Deleting $top/$nickname"
        rm -Rf "$top/$nickname"
    fi
done

echo "Done."


code:
#!/usr/bin/env php
<?php
/*
 * StatusNet - a distributed open-source microblogging tool
 * Copyright (C) 2008, 2009, 2010, StatusNet, Inc.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

define('INSTALLDIR', realpath(dirname(__FILE__) . '/..'));

$shortoptions = 'i::n::y';
$longoptions = array('id=', 'nickname=', 'yes');

$helptext = <<<END_OF_DELETEGROUP_HELP
deletegroup.php [options]
deletes a group from the database

  -i --id       ID of the group
  -n --nickname nickname of the group
  -y --yes      do not wait for confirmation

END_OF_DELETEGROUP_HELP;

require_once INSTALLDIR.'/scripts/commandline.inc';

if (have_option('i', 'id')) {
    $id = get_option_value('i', 'id');
    $group = User_group::getKV('id', $id);
    if (empty($group)) {
        print "Can't find group with ID $id\n";
        exit(1);
    }
} else if (have_option('n', 'nickname')) {
    $nickname = get_option_value('n', 'nickname');
    $local = Local_group::getKV('nickname', $nickname);
    if (empty($local)) {
        print "Can't find group with nickname '$nickname'\n";
        exit(1);
    }
    $group = User_group::getKV('id', $local->group_id);
} else {
    print "You must provide either an ID or a nickname.\n";
    print "\n";
    print $helptext;
    exit(1);
}

if (!have_option('y', 'yes')) {
    print "About to PERMANENTLY delete group '{$group->nickname}' ({$group->id}). Are you sure? [y/N] ";
    $response = fgets(STDIN);
    if (strtolower(trim($response)) != 'y') {
        print "Aborting.\n";
        exit(0);
    }
}

print "Deleting...";
$group->delete();
print "DONE.\n";


code:
#!/usr/bin/env php
<?php
/*
 * StatusNet - a distributed open-source microblogging tool
 * Copyright (C) 2008, 2009, StatusNet, Inc.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

define('INSTALLDIR', realpath(dirname(__FILE__) . '/..'));

$shortoptions = 'i::n::u::y';
$longoptions = array('id=', 'nickname=', 'uri=', 'yes');

$helptext = <<<END_OF_DELETEUSER_HELP
deleteprofile.php [options]
deletes a profile from the database

  -i --id       ID of the profile
  -n --nickname nickname of a local user
  -u --uri      OStatus profile URI (only remote users, requires OStatus plugin)
  -y --yes      do not wait for confirmation

END_OF_DELETEUSER_HELP;

require_once INSTALLDIR.'/scripts/commandline.inc';

if (have_option('i', 'id')) {
    $id = get_option_value('i', 'id');
    $profile = Profile::getKV('id', $id);
    if (!$profile instanceof Profile) {
        print "Can't find profile with ID $id\n";
        exit(1);
    }
} else if (have_option('n', 'nickname')) {
    $nickname = get_option_value('n', 'nickname');
    $user = User::getKV('nickname', $nickname);
    if (!$user instanceof User) {
        print "Can't find user with nickname '$nickname'\n";
        exit(1);
    }
    $profile = $user->getProfile();
} else if (have_option('u', 'uri')) {
    $uri = get_option_value('u', 'uri');
    $oprofile = Ostatus_profile::getKV('uri', $uri);
    if (!$oprofile instanceof Ostatus_profile) {
        print "Can't find profile with URI '$uri'\n";
        exit(1);
    }
    $profile = $oprofile->localProfile();
} else {
    print "You must provide either an ID, a URI or a nickname.\n";
    exit(1);
}

if (!have_option('y', 'yes')) {
    print "About to PERMANENTLY delete profile '".$profile->getNickname()."' ({$profile->id}). Are you sure? [y/N] ";
    $response = fgets(STDIN);
    if (strtolower(trim($response)) != 'y') {
        print "Aborting.\n";
        exit(0);
    }
}

print "Deleting...";
$profile->delete();
print "DONE.\n";


code:
#!/usr/bin/env php
<?php

$shortoptions = '';
$longoptions = array('plugin=');

$helptext = <<<ENDOFHELP
Build HTML documentation from doc comments in source.

Usage: docgen.php [options] output-directory
Options:

  --plugin=...     build docs for given plugin instead of core

ENDOFHELP;

define('INSTALLDIR', realpath(dirname(__FILE__) . '/..'));
set_include_path(INSTALLDIR . DIRECTORY_SEPARATOR . 'extlib' . PATH_SEPARATOR . get_include_path());

$pattern = "*.php *.inc";
$exclude = 'config.php */extlib/* */local/* */plugins/* */scripts/*';
$plugin = false;

require_once 'Console/Getopt.php';
$parser = new Console_Getopt();
$result = $parser->getopt($_SERVER['argv'], $shortoptions, $longoptions);
if (PEAR::isError($result)) {
    print $result->getMessage() . "\n";
    exit(1);
}
list($options, $args) = $result;

foreach ($options as $option) {
    $arg = $option[0];
    if ($arg == '--plugin') {
        $plugin = $options[1];
    } else if ($arg == 'h' || $arg == '--help') {
        print $helptext;
        exit(0);
    }
}

if (isset($args[0])) {
    $outdir = $args[0];
    if (!is_dir($outdir)) {
        echo "Output directory $outdir is not a directory.\n";
        exit(1);
    }
} else {
    print $helptext;
    exit(1);
}

if ($plugin) {
    $exclude = "*/extlib/*";
    $indir = INSTALLDIR . "/plugins/" . $plugin;
    if (!is_dir($indir)) {
        $indir = INSTALLDIR . "/plugins";
        $filename = "{$plugin}Plugin.php";
        if (!file_exists("$indir/$filename")) {
            echo "Can't find plugin $plugin.\n";
            exit(1);
        } else {
            $pattern = $filename;
        }
    }
} else {
    $indir = INSTALLDIR;
}

function getVersion()
{
    // define('GNUSOCIAL_VERSION', '0.9.1');
    $source = file_get_contents(INSTALLDIR . '/lib/common.php');
    if (preg_match('/^\s*define\s*\(\s*[\'"]GNUSOCIAL_VERSION[\'"]\s*,\s*[\'"](.*)[\'"]\s*\)\s*;/m', $source, $matches)) {
        return $matches[1];
    }
    return 'unknown';
}

$replacements = array(
    '%%version%%' => getVersion(),
    '%%indir%%' => $indir,
    '%%pattern%%' => $pattern,
    '%%outdir%%' => $outdir,
    '%%htmlout%%' => $outdir,
    '%%exclude%%' => $exclude,
);

var_dump($replacements);

$template = file_get_contents(dirname(__FILE__) . '/doxygen.tmpl');
$template = strtr($template, $replacements);

$templateFile = tempnam(sys_get_temp_dir(), 'statusnet-doxygen');
file_put_contents($templateFile, $template);

$cmd = "doxygen " . escapeshellarg($templateFile);

$retval = 0;
passthru($cmd, $retval);

if ($retval == 0) {
    echo "Done!\n";
    unlink($templateFile);
    exit(0);
} else {
    echo "Failed! Doxygen config left in $templateFile\n";
    exit($retval);
}