code:
<?php
/**
 * StatusNet, the distributed open-source microblogging tool
 *
 * Database schema utilities
 *
 * PHP version 5
 *
 * LICENCE: 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/>.
 *
 * @category  Database
 * @package   StatusNet
 * @author    Evan Prodromou <evan@status.net>
 * @copyright 2009 StatusNet, Inc.
 * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
 * @link      http://status.net/
 */

if (!defined('STATUSNET')) {
    exit(1);
}

/**
 * Class representing the database schema
 *
 * A class representing the database schema. Can be used to
 * manipulate the schema -- especially for plugins and upgrade
 * utilities.
 *
 * @category Database
 * @package  StatusNet
 * @author   Evan Prodromou <evan@status.net>
 * @author   Brion Vibber <brion@status.net>
 * @license  http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
 * @link     http://status.net/
 */

class Schema
{
    static $_static = null;
    protected $conn = null;

    /**
     * Constructor. Only run once for singleton object.
     */

    protected function __construct($conn = null)
    {
        if (is_null($conn)) {
            // XXX: there should be an easier way to do this.
            $user = new User();
            $conn = $user->getDatabaseConnection();
            $user->free();
            unset($user);
        }

        $this->conn = $conn;
    }

    /**
     * Main public entry point. Use this to get
     * the schema object.
     *
     * @return Schema the Schema object for the connection
     */

    static function get($conn = null)
    {
        if (is_null($conn)) {
            $key = 'default';
        } else {
            $key = md5(serialize($conn->dsn));
        }

        $type = common_config('db', 'type');
        if (empty(self::$_static[$key])) {
            $schemaClass = ucfirst($type).'Schema';
            self::$_static[$key] = new $schemaClass($conn);
        }
        return self::$_static[$key];
    }

    /**
     * Gets a ColumnDef object for a single column.
     *
     * Throws an exception if the table is not found.
     *
     * @param string $table  name of the table
     * @param string $column name of the column
     *
     * @return ColumnDef definition of the column or null
     *                   if not found.
     */

    public function getColumnDef($table, $column)
    {
        $td = $this->getTableDef($table);

        if (!empty($td) && !empty($td->columns)) {
            foreach ($td->columns as $cd) {
                if ($cd->name == $column) {
                    return $cd;
                }
            }
        }

        return null;
    }

    /**
     * Creates a table with the given names and columns.
     *
     * @param string $tableName    Name of the table
     * @param array  $def          Table definition array listing fields and indexes.
     *
     * @return boolean success flag
     */

    public function createTable($tableName, $def)
    {
        $statements = $this->buildCreateTable($tableName, $def);
        return $this->runSqlSet($statements);
    }

    /**
     * Build a set of SQL statements to create a table with the given
     * name and columns.
     *
     * @param string $name    Name of the table
     * @param array  $def     Table definition array
     *
     * @return boolean success flag
     */
    public function buildCreateTable($name, $def)
    {
        $def = $this->validateDef($name, $def);
        $def = $this->filterDef($def);
        $sql = array();

        foreach ($def['fields'] as $col => $colDef) {
            $this->appendColumnDef($sql, $col, $colDef);
        }

        // Primary, unique, and foreign keys are constraints, so go within
        // the CREATE TABLE statement normally.
        if (!empty($def['primary key'])) {
            $this->appendPrimaryKeyDef($sql, $def['primary key']);
        }

        if (!empty($def['unique keys'])) {
            foreach ($def['unique keys'] as $col => $colDef) {
                $this->appendUniqueKeyDef($sql, $col, $colDef);
            }
        }

        if (!empty($def['foreign keys'])) {
            foreach ($def['foreign keys'] as $keyName => $keyDef) {
                $this->appendForeignKeyDef($sql, $keyName, $keyDef);
            }
        }

        // Wrap the CREATE TABLE around the main body chunks...
        $statements = array();
        $statements[] = $this->startCreateTable($name, $def) . "\n" .
                        implode($sql, ",\n") . "\n" .
                        $this->endCreateTable($name, $def);

        // Multi-value indexes are advisory and for best portability
        // should be created as separate statements.
        if (!empty($def['indexes'])) {
            foreach ($def['indexes'] as $col => $colDef) {
                $this->appendCreateIndex($statements, $name, $col, $colDef);
            }
        }
        if (!empty($def['fulltext indexes'])) {
            foreach ($def['fulltext indexes'] as $col => $colDef) {
                $this->appendCreateFulltextIndex($statements, $name, $col, $colDef);
            }
        }

        return $statements;
    }

    /**
     * Set up a 'create table' SQL statement.
     *
     * @param string $name table name
     * @param array $def table definition
     * @param $string
     */
    function startCreateTable($name, array $def)
    {
        return 'CREATE TABLE ' . $this->quoteIdentifier($name)  . ' (';
    }

    /**
     * Close out a 'create table' SQL statement.
     *
     * @param string $name table name
     * @param array $def table definition
     * @return string
     */
    function endCreateTable($name, array $def)
    {
        return ')';
    }

    /**
     * Append an SQL fragment with a column definition in a CREATE TABLE statement.
     *
     * @param array $sql
     * @param string $name
     * @param array $def
     */
    function appendColumnDef(array &$sql, $name, array $def)
    {
        $sql[] = "$name " . $this->columnSql($def);
    }

    /**
     * Append an SQL fragment with a constraint definition for a primary
     * key in a CREATE TABLE statement.
     *
     * @param array $sql
     * @param array $def
     */
    function appendPrimaryKeyDef(array &$sql, array $def)
    {
        $sql[] = "PRIMARY KEY " . $this->buildIndexList($def);
    }

    /**
     * Append an SQL fragment with a constraint definition for a unique
     * key in a CREATE TABLE statement.
     *
     * @param array $sql
     * @param string $name
     * @param array $def
     */
    function appendUniqueKeyDef(array &$sql, $name, array $def)
    {
        $sql[] = "CONSTRAINT $name UNIQUE " . $this->buildIndexList($def);
    }

    /**
     * Append an SQL fragment with a constraint definition for a foreign
     * key in a CREATE TABLE statement.
     *
     * @param array $sql
     * @param string $name
     * @param array $def
     */
    function appendForeignKeyDef(array &$sql, $name, array $def)
    {
        if (count($def) != 2) {
            throw new Exception("Invalid foreign key def for $name: " . var_export($def, true));
        }
        list($refTable, $map) = $def;
        $srcCols = array_keys($map);
        $refCols = array_values($map);
        $sql[] = "CONSTRAINT $name FOREIGN KEY " .
                 $this->buildIndexList($srcCols) .
                 " REFERENCES " .
                 $this->quoteIdentifier($refTable) .
                 " " .
                 $this->buildIndexList($refCols);
    }

    /**
     * Append an SQL statement with an index definition for an advisory
     * index over one or more columns on a table.
     *
     * @param array $statements
     * @param string $table
     * @param string $name
     * @param array $def
     */
    function appendCreateIndex(array &$statements, $table, $name, array $def)
    {
        $statements[] = "CREATE INDEX $name ON $table " . $this->buildIndexList($def);
    }

    /**
     * Append an SQL statement with an index definition for a full-text search
     * index over one or more columns on a table.
     *
     * @param array $statements
     * @param string $table
     * @param string $name
     * @param array $def
     */
    function appendCreateFulltextIndex(array &$statements, $table, $name, array $def)
    {
        throw new Exception("Fulltext index not supported in this database");
    }

    /**
     * Append an SQL statement to drop an index from a table.
     *
     * @param array $statements
     * @param string $table
     * @param string $name
     * @param array $def
     */
    function appendDropIndex(array &$statements, $table, $name)
    {
        $statements[] = "DROP INDEX $name ON " . $this->quoteIdentifier($table);
    }

    function buildIndexList(array $def)
    {
        // @fixme
        return '(' . implode(',', array_map(array($this, 'buildIndexItem'), $def)) . ')';
    }

    function buildIndexItem($def)
    {
        if (is_array($def)) {
            list($name, $size) = $def;
            return $this->quoteIdentifier($name) . '(' . intval($size) . ')';
        }
        return $this->quoteIdentifier($def);
    }

    /**
     * Drops a table from the schema
     *
     * Throws an exception if the table is not found.
     *
     * @param string $name Name of the table to drop
     *
     * @return boolean success flag
     */

    public function dropTable($name)
    {
        global $_PEAR;

        $res = $this->conn->query("DROP TABLE $name");

        if ($_PEAR->isError($res)) {
            PEAR_ErrorToPEAR_Exception($res);
        }

        return true;
    }

    /**
     * Adds an index to a table.
     *
     * If no name is provided, a name will be made up based
     * on the table name and column names.
     *
     * Throws an exception on database error, esp. if the table
     * does not exist.
     *
     * @param string $table       Name of the table
     * @param array  $columnNames Name of columns to index
     * @param string $name        (Optional) name of the index
     *
     * @return boolean success flag
     */

    public function createIndex($table, $columnNames, $name=null)
    {
        global $_PEAR;

        if (!is_array($columnNames)) {
            $columnNames = array($columnNames);
        }

        if (empty($name)) {
            $name = "{$table}_".implode("_", $columnNames)."_idx";
        }

        $res = $this->conn->query("ALTER TABLE $table ".
                                   "ADD INDEX $name (".
                                   implode(",", $columnNames).")");

        if ($_PEAR->isError($res)) {
            PEAR_ErrorToPEAR_Exception($res);
        }

        return true;
    }

    /**
     * Drops a named index from a table.
     *
     * @param string $table name of the table the index is on.
     * @param string $name  name of the index
     *
     * @return boolean success flag
     */

    public function dropIndex($table, $name)
    {
        global $_PEAR;

        $res = $this->conn->query("ALTER TABLE $table DROP INDEX $name");

        if ($_PEAR->isError($res)) {
            PEAR_ErrorToPEAR_Exception($res);
        }

        return true;
    }

    /**
     * Adds a column to a table
     *
     * @param string    $table     name of the table
     * @param ColumnDef $columndef Definition of the new
     *                             column.
     *
     * @return boolean success flag
     */

    public function addColumn($table, $columndef)
    {
        global $_PEAR;

        $sql = "ALTER TABLE $table ADD COLUMN " . $this->_columnSql($columndef);

        $res = $this->conn->query($sql);

        if ($_PEAR->isError($res)) {
            PEAR_ErrorToPEAR_Exception($res);
        }

        return true;
    }

    /**
     * Modifies a column in the schema.
     *
     * The name must match an existing column and table.
     *
     * @param string    $table     name of the table
     * @param ColumnDef $columndef new definition of the column.
     *
     * @return boolean success flag
     */

    public function modifyColumn($table, $columndef)
    {
        global $_PEAR;

        $sql = "ALTER TABLE $table MODIFY COLUMN " .
          $this->_columnSql($columndef);

        $res = $this->conn->query($sql);

        if ($_PEAR->isError($res)) {
            PEAR_ErrorToPEAR_Exception($res);
        }

        return true;
    }

    /**
     * Drops a column from a table
     *
     * The name must match an existing column.
     *
     * @param string $table      name of the table
     * @param string $columnName name of the column to drop
     *
     * @return boolean success flag
     */

    public function dropColumn($table, $columnName)
    {
        global $_PEAR;

        $sql = "ALTER TABLE $table DROP COLUMN $columnName";

        $res = $this->conn->query($sql);

        if ($_PEAR->isError($res)) {
            PEAR_ErrorToPEAR_Exception($res);
        }

        return true;
    }

    /**
     * Ensures that a table exists with the given
     * name and the given column definitions.
     *
     * If the table does not yet exist, it will
     * create the table. If it does exist, it will
     * alter the table to match the column definitions.
     *
     * @param string $tableName name of the table
     * @param array  $def       Table definition array
     *
     * @return boolean success flag
     */

    public function ensureTable($tableName, $def)
    {
        $statements = $this->buildEnsureTable($tableName, $def);
        return $this->runSqlSet($statements);
    }

    /**
     * Run a given set of SQL commands on the connection in sequence.
     * Empty input is ok.
     *
     * @fixme if multiple statements, wrap in a transaction?
     * @param array $statements
     * @return boolean success flag
     */
    function runSqlSet(array $statements)
    {
        global $_PEAR;

        $ok = true;
        foreach ($statements as $sql) {
            if (defined('DEBUG_INSTALLER')) {
                echo "<tt>" . htmlspecialchars($sql) . "</tt><br/>\n";
            }
            $res = $this->conn->query($sql);

            if ($_PEAR->isError($res)) {
                common_debug('PEAR exception on query: '.$sql);
                PEAR_ErrorToPEAR_Exception($res);
            }
        }
        return $ok;
    }

    /**
     * Check a table's status, and if needed build a set
     * of SQL statements which change it to be consistent
     * with the given table definition.
     *
     * If the table does not yet exist, statements will
     * be returned to create the table. If it does exist,
     * statements will be returned to alter the table to
     * match the column definitions.
     *
     * @param string $tableName name of the table
     * @param array  $columns   array of ColumnDef
     *                          objects for the table
     *
     * @return array of SQL statements
     */

    function buildEnsureTable($tableName, array $def)
    {
        try {
            $old = $this->getTableDef($tableName);
        } catch (SchemaTableMissingException $e) {
            return $this->buildCreateTable($tableName, $def);
        }

        // Filter the DB-independent table definition to match the current
        // database engine's features and limitations.
        $def = $this->validateDef($tableName, $def);
        $def = $this->filterDef($def);

        $statements = array();
        $fields = $this->diffArrays($old, $def, 'fields', array($this, 'columnsEqual'));
        $uniques = $this->diffArrays($old, $def, 'unique keys');
        $indexes = $this->diffArrays($old, $def, 'indexes');
        $foreign = $this->diffArrays($old, $def, 'foreign keys');
        $fulltext = $this->diffArrays($old, $def, 'fulltext indexes');

        // Drop any obsolete or modified indexes ahead...
        foreach ($indexes['del'] + $indexes['mod'] as $indexName) {
            $this->appendDropIndex($statements, $tableName, $indexName);
        }

        // Drop any obsolete or modified fulltext indexes ahead...
        foreach ($fulltext['del'] + $fulltext['mod'] as $indexName) {
            $this->appendDropIndex($statements, $tableName, $indexName);
        }

        // For efficiency, we want this all in one
        // query, instead of using our methods.

        $phrase = array();

        foreach ($foreign['del'] + $foreign['mod'] as $keyName) {
            $this->appendAlterDropForeign($phrase, $keyName);
        }

        foreach ($uniques['del'] + $uniques['mod'] as $keyName) {
            $this->appendAlterDropUnique($phrase, $keyName);
        }

        if (isset($old['primary key']) && (!isset($def['primary key']) || $def['primary key'] != $old['primary key'])) {
            $this->appendAlterDropPrimary($phrase);
        }

        foreach ($fields['add'] as $columnName) {
            $this->appendAlterAddColumn($phrase, $columnName,
                    $def['fields'][$columnName]);
        }

        foreach ($fields['mod'] as $columnName) {
            $this->appendAlterModifyColumn($phrase, $columnName,
                    $old['fields'][$columnName],
                    $def['fields'][$columnName]);
        }

        foreach ($fields['del'] as $columnName) {
            $this->appendAlterDropColumn($phrase, $columnName);
        }

        if (isset($def['primary key']) && (!isset($old['primary key']) || $old['primary key'] != $def['primary key'])) {
            $this->appendAlterAddPrimary($phrase, $def['primary key']);
        }

        foreach ($uniques['mod'] + $uniques['add'] as $keyName) {
            $this->appendAlterAddUnique($phrase, $keyName, $def['unique keys'][$keyName]);
        }

        foreach ($foreign['mod'] + $foreign['add'] as $keyName) {
            $this->appendAlterAddForeign($phrase, $keyName, $def['foreign keys'][$keyName]);
        }

        $this->appendAlterExtras($phrase, $tableName, $def);

        if (count($phrase) > 0) {
            $sql = 'ALTER TABLE ' . $tableName . ' ' . implode(",\n", $phrase);
            $statements[] = $sql;
        }

        // Now create any indexes...
        foreach ($indexes['mod'] + $indexes['add'] as $indexName) {
            $this->appendCreateIndex($statements, $tableName, $indexName, $def['indexes'][$indexName]);
        }

        foreach ($fulltext['mod'] + $fulltext['add'] as $indexName) {
            $colDef = $def['fulltext indexes'][$indexName];
            $this->appendCreateFulltextIndex($statements, $tableName, $indexName, $colDef);
        }

        return $statements;
    }

    function diffArrays($oldDef, $newDef, $section, $compareCallback=null)
    {
        $old = isset($oldDef[$section]) ? $oldDef[$section] : array();
        $new = isset($newDef[$section]) ? $newDef[$section] : array();

        $oldKeys = array_keys($old);
        $newKeys = array_keys($new);

        $toadd  = array_diff($newKeys, $oldKeys);
        $todrop = array_diff($oldKeys, $newKeys);
        $same   = array_intersect($newKeys, $oldKeys);
        $tomod  = array();
        $tokeep = array();

        // Find which fields have actually changed definition
        // in a way that we need to tweak them for this DB type.
        foreach ($same as $name) {
            if ($compareCallback) {
                $same = call_user_func($compareCallback, $old[$name], $new[$name]);
            } else {
                $same = ($old[$name] == $new[$name]);
            }
            if ($same) {
                $tokeep[] = $name;
                continue;
            }
            $tomod[] = $name;
        }
        return array('add' => $toadd,
                     'del' => $todrop,
                     'mod' => $tomod,
                     'keep' => $tokeep,
                     'count' => count($toadd) + count($todrop) + count($tomod));
    }

    /**
     * Append phrase(s) to an array of partial ALTER TABLE chunks in order
     * to add the given column definition to the table.
     *
     * @param array $phrase
     * @param string $columnName
     * @param array $cd
     */
    function appendAlterAddColumn(array &$phrase, $columnName, array $cd)
    {
        $phrase[] = 'ADD COLUMN ' .
                    $this->quoteIdentifier($columnName) .
                    ' ' .
                    $this->columnSql($cd);
    }

    /**
     * Append phrase(s) to an array of partial ALTER TABLE chunks in order
     * to alter the given column from its old state to a new one.
     *
     * @param array $phrase
     * @param string $columnName
     * @param array $old previous column definition as found in DB
     * @param array $cd current column definition
     */
    function appendAlterModifyColumn(array &$phrase, $columnName, array $old, array $cd)
    {
        $phrase[] = 'MODIFY COLUMN ' .
                    $this->quoteIdentifier($columnName) .
                    ' ' .
                    $this->columnSql($cd);
    }

    /**
     * Append phrase(s) to an array of partial ALTER TABLE chunks in order
     * to drop the given column definition from the table.
     *
     * @param array $phrase
     * @param string $columnName
     */
    function appendAlterDropColumn(array &$phrase, $columnName)
    {
        $phrase[] = 'DROP COLUMN ' . $this->quoteIdentifier($columnName);
    }

    function appendAlterAddUnique(array &$phrase, $keyName, array $def)
    {
        $sql = array();
        $sql[] = 'ADD';
        $this->appendUniqueKeyDef($sql, $keyName, $def);
        $phrase[] = implode(' ', $sql);
    }

    function appendAlterAddForeign(array &$phrase, $keyName, array $def)
    {
        $sql = array();
        $sql[] = 'ADD';
        $this->appendForeignKeyDef($sql, $keyName, $def);
        $phrase[] = implode(' ', $sql);
    }

    function appendAlterAddPrimary(array &$phrase, array $def)
    {
        $sql = array();
        $sql[] = 'ADD';
        $this->appendPrimaryKeyDef($sql, $def);
        $phrase[] = implode(' ', $sql);
    }

    function appendAlterDropPrimary(array &$phrase)
    {
        $phrase[] = 'DROP CONSTRAINT PRIMARY KEY';
    }

    function appendAlterDropUnique(array &$phrase, $keyName)
    {
        $phrase[] = 'DROP CONSTRAINT ' . $keyName;
    }

    function appendAlterDropForeign(array &$phrase, $keyName)
    {
        $phrase[] = 'DROP FOREIGN KEY ' . $keyName;
    }

    function appendAlterExtras(array &$phrase, $tableName, array $def)
    {
        // no-op
    }

    /**
     * Quote a db/table/column identifier if necessary.
     *
     * @param string $name
     * @return string
     */
    function quoteIdentifier($name)
    {
        return $name;
    }

    function quoteDefaultValue($cd)
    {
        if (($cd['type'] == 'datetime' || $cd['type'] == 'timestamp') && $cd['default'] == 'CURRENT_TIMESTAMP') {
            return $cd['default'];
        } else {
            return $this->quoteValue($cd['default']);
        }
    }

    function quoteValue($val)
    {
        return $this->conn->quoteSmart($val);
    }

    /**
     * Check if two column definitions are equivalent.
     * The default implementation checks _everything_ but in many cases
     * you may be able to discard a bunch of equivalencies.
     *
     * @param array $a
     * @param array $b
     * @return boolean
     */
    function columnsEqual(array $a, array $b)
    {
        return !array_diff_assoc($a, $b) && !array_diff_assoc($b, $a);
    }

    /**
     * Returns the array of names from an array of
     * ColumnDef objects.
     *
     * @param array $cds array of ColumnDef objects
     *
     * @return array strings for name values
     */

    protected function _names($cds)
    {
        $names = array();

        foreach ($cds as $cd) {
            $names[] = $cd->name;
        }

        return $names;
    }

    /**
     * Get a ColumnDef from an array matching
     * name.
     *
     * @param array  $cds  Array of ColumnDef objects
     * @param string $name Name of the column
     *
     * @return ColumnDef matching item or null if no match.
     */

    protected function _byName($cds, $name)
    {
        foreach ($cds as $cd) {
            if ($cd->name == $name) {
                return $cd;
            }
        }

        return null;
    }

    /**
     * Return the proper SQL for creating or
     * altering a column.
     *
     * Appropriate for use in CREATE TABLE or
     * ALTER TABLE statements.
     *
     * @param ColumnDef $cd column to create
     *
     * @return string correct SQL for that column
     */

    function columnSql(array $cd)
    {
        $line = array();
        $line[] = $this->typeAndSize($cd);

        if (isset($cd['default'])) {
            $line[] = 'default';
            $line[] = $this->quoteDefaultValue($cd);
        } else if (!empty($cd['not null'])) {
            // Can't have both not null AND default!
            $line[] = 'not null';
        }

        return implode(' ', $line);
    }

    /**
     *
     * @param string $column canonical type name in defs
     * @return string native DB type name
     */
    function mapType($column)
    {
        return $column;
    }

    function typeAndSize($column)
    {
        //$type = $this->mapType($column);
        $type = $column['type'];
        if (isset($column['size'])) {
            $type = $column['size'] . $type;
        }
        $lengths = array();

        if (isset($column['precision'])) {
            $lengths[] = $column['precision'];
            if (isset($column['scale'])) {
                $lengths[] = $column['scale'];
            }
        } else if (isset($column['length'])) {
            $lengths[] = $column['length'];
        }

        if ($lengths) {
            return $type . '(' . implode(',', $lengths) . ')';
        } else {
            return $type;
        }
    }

    /**
     * Convert an old-style set of ColumnDef objects into the current
     * Drupal-style schema definition array, for backwards compatibility
     * with plugins written for 0.9.x.
     *
     * @param string $tableName
     * @param array $defs: array of ColumnDef objects
     * @return array
     */
    protected function oldToNew($tableName, array $defs)
    {
        $table = array();
        $prefixes = array(
            'tiny',
            'small',
            'medium',
            'big',
        );
        foreach ($defs as $cd) {
            $column = array();
            $column['type'] = $cd->type;
            foreach ($prefixes as $prefix) {
                if (substr($cd->type, 0, strlen($prefix)) == $prefix) {
                    $column['type'] = substr($cd->type, strlen($prefix));
                    $column['size'] = $prefix;
                    break;
                }
            }

            if ($cd->size) {
                if ($cd->type == 'varchar' || $cd->type == 'char') {
                    $column['length'] = $cd->size;
                }
            }
            if (!$cd->nullable) {
                $column['not null'] = true;
            }
            if ($cd->auto_increment) {
                $column['type'] = 'serial';
            }
            if ($cd->default) {
                $column['default'] = $cd->default;
            }
            $table['fields'][$cd->name] = $column;

            if ($cd->key == 'PRI') {
                // If multiple columns are defined as primary key,
                // we'll pile them on in sequence.
                if (!isset($table['primary key'])) {
                    $table['primary key'] = array();
                }
                $table['primary key'][] = $cd->name;
            } else if ($cd->key == 'MUL') {
                // Individual multiple-value indexes are only per-column
                // using the old ColumnDef syntax.
                $idx = "{$tableName}_{$cd->name}_idx";
                $table['indexes'][$idx] = array($cd->name);
            } else if ($cd->key == 'UNI') {
                // Individual unique-value indexes are only per-column
                // using the old ColumnDef syntax.
                $idx = "{$tableName}_{$cd->name}_idx";
                $table['unique keys'][$idx] = array($cd->name);
            }
        }

        return $table;
    }

    /**
     * Filter the given table definition array to match features available
     * in this database.
     *
     * This lets us strip out unsupported things like comments, foreign keys,
     * or type variants that we wouldn't get back from getTableDef().
     *
     * @param array $tableDef
     */
    function filterDef(array $tableDef)
    {
        return $tableDef;
    }

    /**
     * Validate a table definition array, checking for basic structure.
     *
     * If necessary, converts from an old-style array of ColumnDef objects.
     *
     * @param string $tableName
     * @param array $def: table definition array
     * @return array validated table definition array
     *
     * @throws Exception on wildly invalid input
     */
    function validateDef($tableName, array $def)
    {
        if (isset($def[0]) && $def[0] instanceof ColumnDef) {
            $def = $this->oldToNew($tableName, $def);
        }

        // A few quick checks :D
        if (!isset($def['fields'])) {
            throw new Exception("Invalid table definition for $tableName: no fields.");
        }

        return $def;
    }

    function isNumericType($type)
    {
        $type = strtolower($type);
        $known = array('int', 'serial', 'numeric');
        return in_array($type, $known);
    }

    /**
     * Pull info from the query into a fun-fun array of dooooom
     *
     * @param string $sql
     * @return array of arrays
     */
    protected function fetchQueryData($sql)
    {
        global $_PEAR;

        $res = $this->conn->query($sql);
        if ($_PEAR->isError($res)) {
            PEAR_ErrorToPEAR_Exception($res);
        }

        $out = array();
        $row = array();
        while ($res->fetchInto($row, DB_FETCHMODE_ASSOC)) {
            $out[] = $row;
        }
        $res->free();

        return $out;
    }

}

class SchemaTableMissingException extends Exception
{
    // no-op
}


code:
<?php

/**
 * StatusNet, the distributed open-source microblogging tool
 *
 * Database schema utilities
 *
 * PHP version 5
 *
 * LICENCE: 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/>.
 *
 * @category  Database
 * @package   StatusNet
 * @author    Evan Prodromou <evan@status.net>
 * @copyright 2009 StatusNet, Inc.
 * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
 * @link      http://status.net/
 */

if (!defined('GNUSOCIAL')) { exit(1); }

class SchemaUpdater
{
    public function __construct($schema)
    {
        $this->schema = $schema;
        $this->checksums = $this->getChecksums();
    }

    /**
     * @param string $tableName
     * @param array $tableDef
     */
    public function register($tableName, array $tableDef)
    {
        // Check if the table we're registering is related to a Managed_DataObject
        if (is_a(ucfirst($tableName), 'Managed_DataObject', true)) {
            call_user_func("{$tableName}::beforeSchemaUpdate");
        }

        $this->tables[$tableName] = $tableDef;
    }

    /**
     * Go ping em!
     *
     * @fixme handle tables that belong on different database servers...?
     */
    public function checkSchema()
    {
        $checksums = $this->checksums;
        foreach ($this->tables as $table => $def) {
            $checksum = $this->checksum($def);
            if (empty($checksums[$table])) {
                common_log(LOG_DEBUG, "No previous schema_version for $table: updating to $checksum");
            } else if ($checksums[$table] == $checksum) {
                common_log(LOG_DEBUG, "Last schema_version for $table up to date: $checksum");
                continue;
            } else {
                common_log(LOG_DEBUG, "Last schema_version for $table is {$checksums[$table]}: updating to $checksum");
            }
            //$this->conn->query('BEGIN');
            $this->schema->ensureTable($table, $def);
            $this->saveChecksum($table, $checksum);
            //$this->conn->commit();
        }
    }

    /**
     * Calculate a checksum for this table definition array.
     *
     * @param array $def
     * @return string
     */
    public function checksum(array $def)
    {
        $flat = serialize($def);
        return sha1($flat);
    }

    /**
     * Pull all known table checksums into an array for easy lookup.
     *
     * @return array: associative array of table names to checksum strings
     */
    protected function getChecksums()
    {
        $checksums = array();

        try {
            $sv = new Schema_version();
            $sv->find();
            while ($sv->fetch()) {
                $checksums[$sv->table_name] = $sv->checksum;
            }

            return $checksums;
        } catch (Exception $e) {
            // no dice!
            common_log(LOG_DEBUG, "Possibly schema_version table doesn't exist yet.");
        }

        return $checksums;
    }

    /**
     * Save or update current available checksums.
     *
     * @param string $table
     * @param string $checksum
     */
    protected function saveChecksum($table, $checksum)
    {
        try {
            $sv = new Schema_version();
            $sv->table_name = $table;
            $sv->checksum = $checksum;
            $sv->modified = common_sql_now();
            if (isset($this->checksums[$table])) {
                $sv->update();
            } else {
                $sv->insert();
            }
        } catch (Exception $e) {
            // no dice!
            common_log(LOG_DEBUG, "Possibly schema_version table doesn't exist yet.");
        }
        $this->checksums[$table] = $checksum;
    }
}

repo_name: andremichelle/gnu

license: mit


code:
<?php
/**
 * StatusNet - the distributed open-source microblogging tool
 * Copyright (C) 2011, StatusNet, Inc.
 *
 * Filtering notice stream that recognizes notice scope
 *
 * PHP version 5
 *
 * 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/>.
 *
 * @category  Stream
 * @package   StatusNet
 * @author    Evan Prodromou <evan@status.net>
 * @copyright 2011 StatusNet, Inc.
 * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html AGPL 3.0
 * @link      http://status.net/
 */

if (!defined('GNUSOCIAL')) { exit(1); }

/**
 * Class comment
 *
 * @category  Stream
 * @package   StatusNet
 * @author    Evan Prodromou <evan@status.net>
 * @copyright 2011 StatusNet, Inc.
 * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html AGPL 3.0
 * @link      http://status.net/
 */

class ScopingNoticeStream extends FilteringNoticeStream
{
    protected $profile;

    function __construct(NoticeStream $upstream, Profile $scoped=null)
    {
        parent::__construct($upstream);

        $this->profile = $scoped;   // legacy
        $this->scoped = $scoped;
    }

    /**
     * Only return notices where the profile is in scope
     *
     * @param Notice $notice The notice to check
     *
     * @return boolean whether to include the notice
     */

    protected function filter(Notice $notice)
    {
        return $notice->inScope($this->scoped);
    }

    function prefill($notices)
    {
        // XXX: this should probably only be in the scoping one.

        Notice::fillGroups($notices);
        Notice::fillReplies($notices);

        if (common_config('notice', 'hidespam')) {

            $profiles = Notice::getProfiles($notices);

            foreach ($profiles as $profile) {
                $pids[] = $profile->id;
            }

            Profile_role::pivotGet('profile_id',
                                   $pids,
                                   array('role' => Profile_role::SILENCED));
        }
    }
}


code:
<?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/>.
 */

if (!defined('STATUSNET') && !defined('LACONICA')) {
    exit(1);
}

class SearchEngine
{
    protected $target;
    protected $table;

    function __construct($target, $table)
    {
        $this->target = $target;
        $this->table = $table;
    }

    function query($q)
    {
    }

    function limit($offset, $count, $rss = false)
    {
        return $this->target->limit($offset, $count);
    }

    function set_sort_mode($mode)
    {
        switch ($mode) {
            case 'chron':
                return $this->target->orderBy('created DESC');
                break;
            case 'reverse_chron':
                return $this->target->orderBy('created ASC');
                break;
            case 'nickname_desc':
                if ($this->table != 'profile') {
                    throw new Exception(
                        'nickname_desc sort mode can only be use when searching profile.'
                    );
                } else {
                    return $this->target->orderBy(sprintf('%1$s.nickname DESC', $this->table));
                }
                break;
            case 'nickname_asc':
                if ($this->table != 'profile') {
                    throw new Exception(
                        'nickname_desc sort mode can only be use when searching profile.'
                    );
                } else {
                    return $this->target->orderBy(sprintf('%1$s.nickname ASC', $this->table));
                }
                break;
            default:
                return $this->target->orderBy('created DESC');
                break;
        }
    }
}

class MySQLSearch extends SearchEngine
{
    function query($q)
    {
        if ('profile' === $this->table) {
            $this->target->whereAdd(
                sprintf('MATCH (%2$s.nickname, %2$s.fullname, %2$s.location, %2$s.bio, %2$s.homepage) ' .
                    'AGAINST ("%1$s" IN BOOLEAN MODE)',
                    $this->target->escape($q, true),
                    $this->table)
            );
            if (strtolower($q) != $q) {
                $this->target->whereAdd(
                    sprintf('MATCH (%2$s.nickname, %2$s.fullname, %2$s.location, %2$s.bio, %2$s.homepage) ' .
                        'AGAINST ("%1$s" IN BOOLEAN MODE)',
                        $this->target->escape(strtolower($q), true),
                        $this->table),
                    'OR'
                );
            }
            return true;
        } else if ('notice' === $this->table) {

            // Don't show imported notices
            $this->target->whereAdd('notice.is_local != ' . Notice::GATEWAY);

            $this->target->whereAdd(
                sprintf('MATCH (%2$s.content) AGAINST ("%1$s" IN BOOLEAN MODE)',
                    $this->target->escape($q, true),
                    $this->table)
            );
            if (strtolower($q) != $q) {
                $this->target->whereAdd(
                    sprintf('MATCH (%2$s.content) AGAINST ("%1$s" IN BOOLEAN MODE)',
                        $this->target->escape(strtolower($q), true),
                        $this->table),
                    'OR'
                );
            }

            return true;
        } else {
            throw new ServerException('Unknown table: ' . $this->table);
        }
    }
}

class MySQLLikeSearch extends SearchEngine
{
    function query($q)
    {
        if ('profile' === $this->table) {
            $qry = sprintf('(%2$s.nickname LIKE "%%%1$s%%" OR ' .
                           ' %2$s.fullname LIKE "%%%1$s%%" OR ' .
                           ' %2$s.location LIKE "%%%1$s%%" OR ' .
                           ' %2$s.bio      LIKE "%%%1$s%%" OR ' .
                           ' %2$s.homepage LIKE "%%%1$s%%")',
                           $this->target->escape($q, true),
                           $this->table);
        } else if ('notice' === $this->table) {
            $qry = sprintf('content LIKE "%%%1$s%%"', $this->target->escape($q, true));
        } else {
            throw new ServerException('Unknown table: ' . $this->table);
        }

        $this->target->whereAdd($qry);

        return true;
    }
}

class PGSearch extends SearchEngine
{
    function query($q)
    {
        if ('profile' === $this->table) {
            return $this->target->whereAdd('textsearch @@ plainto_tsquery(\'' . $this->target->escape($q) . '\')');
        } else if ('notice' === $this->table) {

            // XXX: We need to filter out gateway notices (notice.is_local = -2) --Zach

            return $this->target->whereAdd('to_tsvector(\'english\', content) @@ plainto_tsquery(\'' . $this->target->escape($q) . '\')');
        } else {
            throw new ServerException('Unknown table: ' . $this->table);
        }
    }
}


code:
<?php
/**
 * Base search action class.
 *
 * PHP version 5
 *
 * @category Action
 * @package  StatusNet
 * @author   Evan Prodromou <evan@status.net>
 * @author   Robin Millette <millette@status.net>
 * @license  http://www.fsf.org/licensing/licenses/agpl.html AGPLv3
 * @link     http://status.net/
 *
 * 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/>.
 */

if (!defined('STATUSNET') && !defined('LACONICA')) {
    exit(1);
}

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

/**
 * Base search action class.
 *
 * @category Action
 * @package  StatusNet
 * @author   Evan Prodromou <evan@status.net>
 * @author   Robin Millette <millette@status.net>
 * @license  http://www.fsf.org/licensing/licenses/agpl.html AGPLv3
 * @link     http://status.net/
 */
class SearchAction extends Action
{
    /**
     * Return true if read only.
     *
     * @return boolean true
     */
    function isReadOnly($args)
    {
        return true;
    }

    function handle()
    {
        parent::handle();
        $this->showPage();
    }

    function showTop($arr=null)
    {
        $error = null;
        if ($arr) {
            $error = $arr[1];
        }
        if (!empty($error)) {
            $this->element('p', 'error', $error);
        } else {
            $instr = $this->getInstructions();
            $output = common_markup_to_html($instr);
            $this->elementStart('div', 'instructions');
            $this->raw($output);
            $this->elementEnd('div');
        }
    }

    function title()
    {
        return null;
    }

    function showContent() {
        $this->showTop();
        $this->showForm();
    }

    function showForm($error=null)
    {
        $q = $this->trimmed('q');
        $page = $this->trimmed('page', 1);
        $this->elementStart('form', array('method' => 'get',
                                           'id' => 'form_search',
                                           'class' => 'form_settings',
                                           'action' => common_local_url($this->trimmed('action'))));
        $this->elementStart('fieldset');
        // TRANS: Fieldset legend for the search form.
        $this->element('legend', null, _('Search site'));
        $this->elementStart('ul', 'form_data');
        $this->elementStart('li');
        if (!common_config('site', 'fancy')) {
            $this->hidden('action', $this->trimmed('action'));
        }
        // TRANS: Used as a field label for the field where one or more keywords
        // TRANS: for searching can be entered.
        $this->input('q', _('Keyword(s)'), $q);
        // TRANS: Button text for searching site.
        $this->element('input', array('type'=>'submit', 'class'=>'submit', 'value'=>_m('BUTTON','Search')));
        $this->elementEnd('li');
        $this->elementEnd('ul');
        $this->elementEnd('fieldset');
        $this->elementEnd('form');
        if ($q) {
            $this->showResults($q, $page);
        }
    }

    function searchSuggestions($q) {
        // Don't change these long strings to HEREDOC; xgettext won't pick them up.
        // TRANS: Standard search suggestions shown when a search does not give any results.
        $message = _("* Make sure all words are spelled correctly.
* Try different keywords.
* Try more general keywords.
* Try fewer keywords.");
            $message .= "\n";

        if (!common_config('site', 'private')) {
            $qe = urlencode($q);
            $message .= "\n";
            // Don't change these long strings to HEREDOC; xgettext won't pick them up.
            // TRANS: Standard search suggestions shown when a search does not give any results.
            $message .= sprintf(_("You can also try your search on other engines:

* [DuckDuckGo](https://duckduckgo.com/?q=site%%3A%%%%site.server%%%%+%s)
* [Ixquick](https://ixquick.com/do/search?query=site%%3A%%%%site.server%%%%+%s)
* [Searx](https://searx.laquadrature.net/?q=site%%3A%%%%site.server%%%%+%s)
* [Yahoo!](https://search.yahoo.com/search?p=site%%3A%%%%site.server%%%%+%s)
"), $qe, $qe, $qe, $qe);
            $message .= "\n";
        }
        $this->elementStart('div', 'help instructions');
        $this->raw(common_markup_to_html($message));
        $this->elementEnd('div');
    }
}


code:
<?php
/**
 * StatusNet - the distributed open-source microblogging tool
 * Copyright (C) 2011, StatusNet, Inc.
 *
 * Form for searching a StatusNet site
 *
 * PHP version 5
 *
 * 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/>.
 *
 * @category  Widget
 * @package   StatusNet
 * @author    Evan Prodromou <evan@status.net>
 * @copyright 2011 StatusNet, Inc.
 * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html AGPL 3.0
 * @link      http://status.net/
 */

if (!defined('STATUSNET')) {
    // This check helps protect against security problems;
    // your code file can't be executed directly from the web.
    exit(1);
}

/**
 * Form for searching a StatusNet site
 *
 * @category  General
 * @package   StatusNet
 * @author    Evan Prodromou <evan@status.net>
 * @copyright 2011 StatusNet, Inc.
 * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html AGPL 3.0
 * @link      http://status.net/
 */
class SearchForm extends Form
{
    /**
     * Visible or invisible data elements
     *
     * Display the form fields that make up the data of the form.
     * Sub-classes should overload this to show their data.
     *
     * @return void
     */
    function formData()
    {
        $this->out->element('input', array('name' => 'q',
                                           'size' => 20,
                                           'id' => 'search-q'));
    }

    /**
     * Buttons for form actions
     *
     * Submit and cancel buttons (or whatever)
     * Sub-classes should overload this to show their own buttons.
     *
     * @return void
     */
    function formActions()
    {
        $this->out->element('input', array('type' => 'submit',
                                           // TRANS: Button text for search button on search form.
                                           'value' => _m('BUTTON','Search')));
    }

    /**
     * ID of the form
     *
     * Should be unique on the page. Sub-classes should overload this
     * to show their own IDs.
     *
     * @return int ID of the form
     */
    function id()
    {
        return 'header-search';
    }

    /**
     * Action of the form.
     *
     * URL to post to. Should be overloaded by subclasses to give
     * somewhere to post to.
     *
     * @return string URL to post to
     */
    function action()
    {
        return common_local_url('noticesearch');
    }

    function method()
    {
        return 'get';
    }
}


code:
<?php
/**
 * StatusNet, the distributed open-source microblogging tool
 *
 * Menu for search group of actions
 *
 * PHP version 5
 *
 * LICENCE: 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/>.
 *
 * @category  Menu
 * @package   StatusNet
 * @author    Evan Prodromou <evan@status.net>
 * @copyright 2008-2011 StatusNet, Inc.
 * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
 * @link      http://status.net/
 */

if (!defined('STATUSNET') && !defined('LACONICA')) {
    exit(1);
}

/**
 * Menu for public group of actions
 *
 * @category Menu
 * @package  StatusNet
 * @author   Evan Prodromou <evan@status.net>
 * @license  http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
 * @link     http://status.net/
 *
 * @see      Widget
 */
class SearchGroupNav extends Menu
{
    var $q = null;

    /**
     * Construction
     *
     * @param Action $action current action, used for output
     */
    function __construct(Action $action=null, $q = null)
    {
        parent::__construct($action);
        $this->q = $q;
    }

    /**
     * Show the menu
     *
     * @return void
     */
    function show()
    {
        $action_name = $this->action->trimmed('action');
        $this->action->elementStart('ul', array('class' => 'nav'));
        $args = array();
        if ($this->q) {
            $args['q'] = $this->q;
        }
        // TRANS: Menu item in search group navigation panel.
        $this->out->menuItem(common_local_url('peoplesearch', $args), _m('MENU','People'),
            // TRANS: Menu item title in search group navigation panel.
            _('Find people on this site'), $action_name == 'peoplesearch', 'nav_search_people');
        // TRANS: Menu item in search group navigation panel.
        $this->out->menuItem(common_local_url('noticesearch', $args), _m('MENU','Notices'),
            // TRANS: Menu item title in search group navigation panel.
            _('Find content of notices'), $action_name == 'noticesearch', 'nav_search_notice');
        // TRANS: Menu item in search group navigation panel.
        $this->out->menuItem(common_local_url('groupsearch', $args), _m('MENU','Groups'),
            // TRANS: Menu item title in search group navigation panel.
            _('Find groups on this site'), $action_name == 'groupsearch', 'nav_search_group');
        $this->action->elementEnd('ul');
    }
}


code:
<?php
/**
 * StatusNet - the distributed open-source microblogging tool
 * Copyright (C) 2011, StatusNet, Inc.
 *
 * Stream of notice results
 *
 * PHP version 5
 *
 * 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/>.
 *
 * @category  Stream
 * @package   StatusNet
 * @author    Evan Prodromou <evan@status.net>
 * @copyright 2011 StatusNet, Inc.
 * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html AGPL 3.0
 * @link      http://status.net/
 */

if (!defined('GNUSOCIAL')) { exit(1); }

/**
 * Stream of notice search results
 *
 * @category  General
 * @package   StatusNet
 * @author    Evan Prodromou <evan@status.net>
 * @copyright 2011 StatusNet, Inc.
 * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html AGPL 3.0
 * @link      http://status.net/
 */

class SearchNoticeStream extends ScopingNoticeStream
{
    function __construct($q, Profile $scoped=null)
    {
        parent::__construct(new RawSearchNoticeStream($q), $scoped);
    }
}

class RawSearchNoticeStream extends NoticeStream
{
    protected $q;

    function __construct($q)
    {
        $this->q = $q;
    }

    function getNoticeIds($offset, $limit, $since_id, $max_id)
    {
        $notice = new Notice();

        $search_engine = $notice->getSearchEngine('notice');
        $search_engine->set_sort_mode('chron');

        $search_engine->limit($offset, $limit);

        $ids = array();

        // wtf?

        $search_engine->query($this->q);

        if ($notice->find()) {
            while ($notice->fetch()) {
                $ids[] = $notice->id;
            }
        }

        return $ids;
    }
}


code:
<?php
/**
 * StatusNet - the distributed open-source microblogging tool
 * Copyright (C) 2011, StatusNet, Inc.
 *
 * Secondary menu, shown at foot of all pages
 *
 * PHP version 5
 *
 * 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/>.
 *
 * @category  Cache
 * @package   StatusNet
 * @author    Evan Prodromou <evan@status.net>
 * @copyright 2011 StatusNet, Inc.
 * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html AGPL 3.0
 * @link      http://status.net/
 */

if (!defined('STATUSNET')) {
    // This check helps protect against security problems;
    // your code file can't be executed directly from the web.
    exit(1);
}

/**
 * Secondary menu, shown at the bottom of all pages
 *
 * @category  General
 * @package   StatusNet
 * @author    Evan Prodromou <evan@status.net>
 * @copyright 2011 StatusNet, Inc.
 * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html AGPL 3.0
 * @link      http://status.net/
 */
class SecondaryNav extends Menu
{
    function show()
    {
        $this->out->elementStart('ul', array('class' => 'nav',
                                             'id' => 'site_nav_global_secondary'));
        if (Event::handle('StartSecondaryNav', array($this->action))) {
            $this->out->menuItem(common_local_url('doc', array('title' => 'help')),
                                 // TRANS: Secondary navigation menu item leading to help on StatusNet.
                                 _m('MENU','Help'));
            $this->out->menuItem(common_local_url('doc', array('title' => 'about')),
                                 // TRANS: Secondary navigation menu item leading to text about StatusNet site.
                                 _m('MENU','About'));
            $this->out->menuItem(common_local_url('doc', array('title' => 'faq')),
                                 // TRANS: Secondary navigation menu item leading to Frequently Asked Questions.
                                 _m('MENU','FAQ'));
            $bb = common_config('site', 'broughtby');
            if (!empty($bb)) {
                $this->out->menuItem(common_local_url('doc', array('title' => 'tos')),
                                     // TRANS: Secondary navigation menu item leading to Terms of Service.
                                     _m('MENU','TOS'));
            }
            $this->out->menuItem(common_local_url('doc', array('title' => 'privacy')),
                                 // TRANS: Secondary navigation menu item leading to privacy policy.
                                 _m('MENU','Privacy'));
            $this->out->menuItem(common_local_url('doc', array('title' => 'source')),
                                 // TRANS: Secondary navigation menu item. Leads to information about StatusNet and its license.
                                 _m('MENU','Source'));
            $this->out->menuItem(common_local_url('version'),
                                 // TRANS: Secondary navigation menu item leading to version information on the StatusNet site.
                                 _m('MENU','Version'));
            $this->out->menuItem(common_local_url('doc', array('title' => 'contact')),
                                 // TRANS: Secondary navigation menu item leading to e-mail contact information on the
                                 // TRANS: StatusNet site, where to report bugs, ...
                                 _m('MENU','Contact'));
            Event::handle('EndSecondaryNav', array($this->action));
        }
        $this->out->elementEnd('ul');
    }
}


code:
<?php
/**
 * StatusNet, the distributed open-source microblogging tool
 *
 * Base class for sections (sidebar widgets)
 *
 * PHP version 5
 *
 * LICENCE: 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/>.
 *
 * @category  Widget
 * @package   StatusNet
 * @author    Evan Prodromou <evan@status.net>
 * @copyright 2009 StatusNet, Inc.
 * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
 * @link      http://status.net/
 */

if (!defined('GNUSOCIAL') && !defined('STATUSNET')) { exit(1); }

/**
 * Base class for sections
 *
 * These are the widgets that show interesting data about a person
 * group, or site.
 *
 * @category Widget
 * @package  StatusNet
 * @author   Evan Prodromou <evan@status.net>
 * @license  http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
 * @link     http://status.net/
 */
abstract class Section extends Widget
{
    /**
     * Show the form
     *
     * Uses a recipe to output the form.
     *
     * @return void
     * @see Widget::show()
     */
    function show()
    {
        $this->out->elementStart('div',
                                 array('id' => $this->divId(),
                                       'class' => 'section'));

        $this->showTitle();

        $have_more = $this->showContent();

        if ($have_more) {
            $this->showMore();
        }

        $this->out->elementEnd('div');
    }

    function showTitle()
    {
        $link = $this->link();
        if (!empty($link)) {
            $this->out->elementStart('h2');
            $this->out->element('a', array('href' => $link), $this->title());
            $this->out->elementEnd('h2');
        } else {
            $this->out->element('h2', null,
                                $this->title());
        }
    }

    function showMore()
    {
        $this->out->elementStart('p');
        $this->out->element('a', array('href' => $this->moreUrl(),
                                       'class' => 'more'),
                            $this->moreTitle());
        $this->out->elementEnd('p');
    }

    abstract public function divId();

    function title()
    {
        // TRANS: Default title for section/sidebar widget.
        return _('Untitled section');
    }

    function link()
    {
        return null;
    }

    function showContent()
    {
        $this->out->element('p', null,
                            // TRANS: Default content for section/sidebar widget.
                            _('(None)'));
        return false;
    }

    function moreUrl()
    {
        return null;
    }

    function moreTitle()
    {
        // TRANS: Default "More..." title for section/sidebar widget.
        return _('More...');
    }
}


code:
<?php
/**
 * StatusNet, the distributed open-source microblogging tool
 *
 * widget for displaying a list of notices
 *
 * PHP version 5
 *
 * LICENCE: 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/>.
 *
 * @category  UI
 * @package   StatusNet
 * @author    Evan Prodromou <evan@status.net>
 * @author    Sarven Capadisli <csarven@status.net>
 * @copyright 2008 StatusNet, Inc.
 * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
 * @link      http://status.net/
 */

if (!defined('GNUSOCIAL') && !defined('STATUSNET')) { exit(1); }

/**
 * widget for displaying a list of notices in the primary content area
 *
 * @category UI
 * @package  StatusNet
 * @author   Evan Prodromou <evan@status.net>
 * @license  http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
 * @link     http://status.net/
 * @see      Notice
 * @see      NoticeListItem
 * @see      ProfileNoticeList
 */
class SectionNoticeList extends NoticeList
{
    protected $addressees = false;
    protected $attachments = false;
    protected $maxchars = 140;
    protected $options = false;
    protected $show_n = NOTICES_PER_SECTION;
}


code:
<?php
/**
 * StatusNet, the distributed open-source microblogging tool
 *
 * Tags for a profile
 *
 * PHP version 5
 *
 * LICENCE: 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/>.
 *
 * @category  Action
 * @package   StatusNet
 * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
 * @link      http://status.net/
 */

if (!defined('GNUSOCIAL')) { exit(1); }

class SelftagsWidget extends PeopletagsWidget
{
    public function url()
    {
        // link to self tag page
        return common_local_url('selftag', array('tag' => $this->tag->tag));
    }

    function label()
    {
        // TRANS: Label in self tags widget.
        return _m('LABEL','Tags');
    }
}


code:
<?php

/**
 * Server error action.
 *
 * PHP version 5
 *
 * @category Action
 * @package  StatusNet
 * @author   Evan Prodromou <evan@status.net>
 * @author   Zach Copley <zach@status.net>
 * @license  http://www.fsf.org/licensing/licenses/agpl.html AGPLv3
 * @link     http://status.net/
 *
 * 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/>.
 */

if (!defined('GNUSOCIAL')) {
    exit(1);
}

/**
 * Class for displaying HTTP server errors
 *
 * Note: The older util.php class simply printed a string, but the spec
 * says that 500 errors should be treated similarly to 400 errors, and
 * it's easier to give an HTML response.  Maybe we can customize these
 * to display some funny animal cartoons.  If not, we can probably role
 * these classes up into a single class.
 *
 * See: http://tools.ietf.org/html/rfc2616#section-10
 *
 * @category Action
 * @package  StatusNet
 * @author   Zach Copley <zach@status.net>
 * @license  http://www.fsf.org/licensing/licenses/agpl.html AGPLv3
 * @link     http://status.net/
 */
class ServerErrorAction extends ErrorAction
{
    static $status = [500 => 'Internal Server Error',
                      501 => 'Not Implemented',
                      502 => 'Bad Gateway',
                      503 => 'Service Unavailable',
                      504 => 'Gateway Timeout',
                      505 => 'HTTP Version Not Supported'];

    function __construct($message = 'Error', $code = 500, $ex = null)
    {
        parent::__construct($message, $code);

        $this->default = 500;

        if (!$this->code || $this->code < 500 || $this->code > 599) {
            $this->code = $this->default;
        }

        if (!$this->message) {
            $this->message = "Server Error $this->code";
        }

        // Server errors must be logged.
        $log = "ServerErrorAction: $code $message";
        if ($ex) {
            $log .= "\n" . $ex->getTraceAsString();
        }
        common_log(LOG_ERR, $log);

        $this->showPage();
    }

    /**
     *  To specify additional HTTP headers for the action
     *
     * @return void
     */
    function extraHeaders()
    {
        $status_string = self::$status[$this->code];
        header('HTTP/1.1 ' . $this->code . ' ' . $status_string);
    }

    /**
     * Page title.
     *
     * @return string page title
     */

    function title()
    {
        return self::$status[$this->code];
    }

}


code:
<?php
/**
 * StatusNet, the distributed open-source microblogging tool
 *
 * class for a server exception (user error)
 *
 * PHP version 5
 *
 * LICENCE: 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/>.
 *
 * @category  Exception
 * @package   StatusNet
 * @author    Evan Prodromou <evan@status.net>
 * @copyright 2008-2010 StatusNet, Inc.
 * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
 * @link      http://status.net/
 */

if (!defined('STATUSNET') && !defined('LACONICA')) {
    exit(1);
}

/**
 * Class for server exceptions
 *
 * Subclass of PHP Exception for server errors. The user typically can't fix these.
 *
 * @category Exception
 * @package  StatusNet
 * @author   Evan Prodromou <evan@status.net>
 * @license  http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
 * @link     http://status.net/
 */

class ServerException extends Exception
{
    public function __construct($message = "", $code = 500) {
        parent::__construct($message, $code);
    }

    public function __toString() {
        return __CLASS__ . ": [{$this->code}]: {$this->message}\n";
    }
}


code:
<?php
/**
 * StatusNet, the distributed open-source microblogging tool
 *
 * Base class for settings actions
 *
 * PHP version 5
 *
 * LICENCE: 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/>.
 *
 * @category  Settings
 * @package   StatusNet
 * @author    Evan Prodromou <evan@status.net>
 * @copyright 2008-2009 StatusNet, Inc.
 * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
 * @link      http://status.net/
 */

if (!defined('GNUSOCIAL')) { exit(1); }

/**
 * Base class for settings group of actions
 *
 * @category Settings
 * @package  StatusNet
 * @author   Evan Prodromou <evan@status.net>
 * @license  http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
 * @link     http://status.net/
 *
 * @see      Widget
 */

class SettingsAction extends FormAction
{
    /**
     * Show the local navigation menu
     *
     * This is the same for all settings, so we show it here.
     *
     * @return void
     */

    function showLocalNav()
    {
        $menu = new SettingsNav($this);
        $menu->show();
    }

    /**
     * Show notice form.
     *
     * @return nothing
     */

    function showNoticeForm()
    {
        return;
    }

    function showProfileBlock()
    {
    }
}


code:
<?php
/**
 * StatusNet - the distributed open-source microblogging tool
 * Copyright (C) 2010,2011, StatusNet, Inc.
 *
 * Settings menu
 *
 * PHP version 5
 *
 * 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/>.
 *
 * @category  Widget
 * @package   StatusNet
 * @author    Evan Prodromou <evan@status.net>
 * @copyright 2010,2011 StatusNet, Inc.
 * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html AGPL 3.0
 * @link      http://status.net/
 */

if (!defined('STATUSNET')) {
    // This check helps protect against security problems;
    // your code file can't be executed directly from the web.
    exit(1);
}

/**
 * A widget for showing the settings group local nav menu
 *
 * @category Widget
 * @package  StatusNet
 * @author   Evan Prodromou <evan@status.net>
 * @license  http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
 * @link     http://status.net/
 *
 * @see      HTMLOutputter
 */
class SettingsNav extends Menu
{
    /**
     * Show the menu
     *
     * @return void
     */
    function show()
    {
        $actionName = $this->action->trimmed('action');
        $user = common_current_user();
        $nickname = $user->nickname;
        $name = $user->getProfile()->getBestName();

        $stub = new HomeStubNav($this->action);
        $this->submenu(_m('MENU','Home'), $stub);

        $this->action->elementStart('ul');
        $this->action->elementStart('li');
        // TRANS: Header in settings navigation panel.
        $this->action->element('h3', null, _m('HEADER','Settings'));
        $this->action->elementStart('ul', array('class' => 'nav'));

        if (Event::handle('StartAccountSettingsNav', array(&$this->action))) {
            $this->action->menuItem(common_local_url('profilesettings'),
                                    // TRANS: Menu item in settings navigation panel.
                                    _m('MENU','Profile'),
                                    // TRANS: Menu item title in settings navigation panel.
                                    _('Change your profile settings'),
                                    $actionName == 'profilesettings');

            $this->action->menuItem(common_local_url('avatarsettings'),
                                    // TRANS: Menu item in settings navigation panel.
                                    _m('MENU','Avatar'),
                                    // TRANS: Menu item title in settings navigation panel.
                                    _('Upload an avatar'),
                                    $actionName == 'avatarsettings');

            $this->action->menuItem(common_local_url('passwordsettings'),
                                    // TRANS: Menu item in settings navigation panel.
                                    _m('MENU','Password'),
                                    // TRANS: Menu item title in settings navigation panel.
                                    _('Change your password'),
                                    $actionName == 'passwordsettings');

            $this->action->menuItem(common_local_url('emailsettings'),
                                    // TRANS: Menu item in settings navigation panel.
                                    _m('MENU','Email'),
                                    // TRANS: Menu item title in settings navigation panel.
                                    _('Change email handling'),
                                    $actionName == 'emailsettings');

            $this->action->menuItem(common_local_url('urlsettings'),
                                    // TRANS: Menu item in settings navigation panel.
                                    _m('MENU','URL'),
                                    // TRANS: Menu item title in settings navigation panel.
                                    _('URL shorteners'),
                                    $actionName == 'urlsettings');

            Event::handle('EndAccountSettingsNav', array(&$this->action));

            $haveImPlugin = false;

            Event::handle('HaveImPlugin', array(&$haveImPlugin));

            if ($haveImPlugin) {
                $this->action->menuItem(common_local_url('imsettings'),
                                        // TRANS: Menu item in settings navigation panel.
                                        _m('MENU','IM'),
                                        // TRANS: Menu item title in settings navigation panel.
                                        _('Updates by instant messenger (IM)'),
                                        $actionName == 'imsettings');
            }

            if (common_config('sms', 'enabled')) {
                $this->action->menuItem(common_local_url('smssettings'),
                                        // TRANS: Menu item in settings navigation panel.
                                        _m('MENU','SMS'),
                                        // TRANS: Menu item title in settings navigation panel.
                                        _('Updates by SMS'),
                                        $actionName == 'smssettings');
            }

            $this->action->menuItem(common_local_url('oauthconnectionssettings'),
                                    // TRANS: Menu item in settings navigation panel.
                                    _m('MENU','Connections'),
                                    // TRANS: Menu item title in settings navigation panel.
                                    _('Authorized connected applications'),
                                    $actionName == 'oauthconnectionsettings');

            if (common_config('oldschool', 'enabled')) {
                $this->action->menuItem(common_local_url('oldschoolsettings'),
                                        // TRANS: Menu item in settings navigation panel.
                                        _m('MENU','Old school'),
                                        // TRANS: Menu item title in settings navigation panel.
                                        _('UI tweaks for old-school users'),
                                        $actionName == 'oldschoolsettings');
            }

            Event::handle('EndConnectSettingsNav', array(&$this->action));
        }

        $this->action->elementEnd('ul');
        $this->action->elementEnd('li');
        $this->action->elementEnd('ul');
    }
}


code:
<?php
/**
 * StatusNet, the distributed open-source microblogging tool
 *
 * Form for silencing a user
 *
 * PHP version 5
 *
 * LICENCE: 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/>.
 *
 * @category  Form
 * @package   StatusNet
 * @author    Evan Prodromou <evan@status.net>
 * @copyright 2009 StatusNet, Inc.
 * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
 * @link      http://status.net/
 */

if (!defined('STATUSNET')) {
    exit(1);
}

/**
 * Form for silencing a user
 *
 * @category Form
 * @package  StatusNet
 * @author   Evan Prodromou <evan@status.net>
 * @license  http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
 * @link     http://status.net/
 *
 * @see      UnSilenceForm
 */
class SilenceForm extends ProfileActionForm
{
    /**
     * Action this form provides
     *
     * @return string Name of the action, lowercased.
     */
    function target()
    {
        return 'silence';
    }

    /**
     * Title of the form
     *
     * @return string Title of the form, internationalized
     */
    function title()
    {
        // TRANS: Title of form to silence a user.
        return _m('TITLE','Silence');
    }

    /**
     * Description of the form
     *
     * @return string description of the form, internationalized
     */
    function description()
    {
        // TRANS: Description of form to silence a user.
        return _('Silence this user');
    }
}


code:
<?php
/**
 * StatusNet, the distributed open-source microblogging tool
 *
 * A site profile is a set of default settings for a particular style of
 * StatusNet site: public, private, community, etc.
 *
 * PHP version 5
 *
 * LICENCE: 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/>.
 *
 * @category  Installation
 * @package   StatusNet
 * @author    Zach Copley <zach@status.net>
 * @copyright 2011 StatusNet, Inc.
 * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
 * @link      http://status.net/
 */

if (!defined('GNUSOCIAL')) {
    exit(1);
}

/**
 * Helper class for getting the settings for a particular site profile
 */
class SiteProfile
{
    /**
     * Returns the config settings for a site profile by name
     *
     * @param  string $name name of a site profile
     * @return array  config settings
     */
    static public function getSettings($name)
    {
        $sprofileClass = ucfirst($name) . "Site";

        if (class_exists($sprofileClass)) {
            return call_user_func(array($sprofileClass, 'getSettings'));
        } else {
            common_log(
                LOG_ERR,
                "Unknown site profile '{$name}' specified in config file.",
                __FILE__
            );
            return array();
        }
    }
}

/**
 * Site profile settings contain the list of the default settings (and
 * possibly other information for a particular flavor of StatusNet
 * installation). These will overwrite base defaults in $config global.
 *
 * @category Installation
 * @package  StatusNet
 * @author   Zach Copley <zach@status.net>
 * @license  http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
 * @link     http://status.net/
 */
abstract class SiteProfileSettings
{
    static function getSettings()
    {
        throw new MethodNotImplementedException(__METHOD__);
    }

    static function corePlugins() {
        return common_config('plugins', 'core');
    }
    static function defaultPlugins() {
        return common_config('plugins', 'default');
    }
}

/**
 * Settings for a 'public' site
 */
class PublicSite extends SiteProfileSettings
{
    /**
     * Get the settings for this site profile
     *
     * @return type array   an array of settings
     */
    static function getSettings() {
        global $config;
        return array(
            // We only want to change these values, not replace entire 'site' array
            'site' => array_merge(
                $config['site'], array(
                    'inviteonly' => false,
                    'private'    => false,
                    'closed'     => false
                )
            ),
            'plugins' => array(
                'core'    => self::corePlugins(),
                'default' => array_merge(self::defaultPlugins(), array(
                    'RegisterThrottle'        => array(),
                ))
            ),
            'discovery' => array('cors' => true) // Allow Cross-Origin Resource Sharing for service discovery (host-meta, XRD, etc.)
        );
    }
}

/**
 * Settings for a 'private' site
 *
 * // XXX Too business oriented?
 */
class PrivateSite extends SiteProfileSettings
{
    /**
     * Get the settings for this site profile
     *
     * @return type array  an array of settings
     */
    static function getSettings() {
        global $config;
        return array(
            // We only want to change these values, not replace entire 'site' array
            'site' => array_merge(
                $config['site'], array(
                    'inviteonly' => true,
                    'private'    => true,
                )
            ),
            'plugins' => array(
                'core'    => self::corePlugins(),
                'default' => array_merge(self::defaultPlugins(), array(
                    'ExtendedProfile'         => array(),
                    'EmailRegistration'       => array(),
                    'MobileProfile'           => array(),
                )),
                'disable-OStatus' => 1,
                'disable-WebFinger' => 1,
             ),
            'public'        => array('localonly' => true),
            'profile'       => array('delete' => 'true'),
            'license'       => array('type'   => 'private'),
            'attachments'   => array(
                // Only allow uploads of pictures and MS Office files
                'supported' => array(
                    'image/png',
                    'image/jpeg',
                    'image/gif',
                    'image/svg+xml',
                    'application/pdf',
                    'application/msword',
                    'application/vnd.ms-office',
                    'application/vnd.ms-excel',
                    'application/vnd.ms-powerpoint',
                    'application/ogg'
                )
             ),
            'discovery' => array('cors'   => false) // Allow Cross-Origin Resource Sharing for service discovery (host-meta, XRD, etc.)
        );
    }
}

/**
 * Settings for a 'community' site
 */
class CommunitySite extends SiteProfileSettings
{
    /**
     * Get the settings for this site profile
     *
     * @return type array  an array of settings
     */
    static function getSettings() {
        global $config;
        return array(
            // We only want to change these values, not replace entire 'site' array
            'site' => array_merge(
                $config['site'], array(
                    'private'    => false,
                    'inviteonly' => true,
                    'closed'     => false
                )
            ),
            'plugins' => array(
                'core'    => self::corePlugins(),
                'default' => array_merge(self::defaultPlugins(), array(
                ))
            ),
            'public'    => array('localonly' => true),
            'discovery' => array('cors' => true) // Allow Cross-Origin Resource Sharing for service discovery (host-meta, XRD, etc.)
        );
    }

}

/**
 * Settings for a 'singleuser' site
 */
class SingleuserSite extends SiteProfileSettings
{
    /**
     * Get the settings for this site profile
     *
     * @return type array  an array of settings
     */
    static function getSettings() {
        global $config;
        return array(
            'singleuser' => array('enabled' => true),
            // We only want to change these values, not replace entire 'site' array
            'site' => array_merge(
                $config['site'], array(
                    'private'    => false,
                    'closed'     => true,
                    'localonly'  => true,
                )
            ),
            'plugins' => array(
                'core'    => self::corePlugins(),
                'default' => array_merge(self::defaultPlugins(), array(
                    'MobileProfile'           => array(),
                )),
                'disable-Directory' => 1,
            ),
            'public'    => array('localonly' => true),
            'discovery' => array('cors' => true) // Allow Cross-Origin Resource Sharing for service discovery (host-meta, XRD, etc.)
        );
    }

}


code:
<?php

if (!defined('GNUSOCIAL')) { exit(1); }

// Farther than any human will go

define('MAX_PUBLIC_PAGE', 100);

class SitestreamAction extends ManagedAction
{
    /**
     * page of the stream we're on; default = 1
     */

    var $page = null;
    var $notice;

    protected $stream = null;

    function isReadOnly($args)
    {
        return true;
    }

    protected function doPreparation()
    {
        $this->page = ($this->arg('page')) ? ($this->arg('page')+0) : 1;

        if ($this->page > MAX_PUBLIC_PAGE) {
            // TRANS: Client error displayed when requesting a public timeline page beyond the page limit.
            // TRANS: %s is the page limit.
            $this->clientError(sprintf(_('Beyond the page limit (%s).'), MAX_PUBLIC_PAGE));
        }

        common_set_returnto($this->selfUrl());

        $this->streamPrepare();

        $this->notice = $this->stream->getNotices(($this->page-1)*NOTICES_PER_PAGE,
                                            NOTICES_PER_PAGE + 1);

        if (!$this->notice) {
            // TRANS: Server error displayed when a public timeline cannot be retrieved.
            $this->serverError(_('Could not retrieve public timeline.'));
        }

        if ($this->page > 1 && $this->notice->N == 0){
            // TRANS: Client error when page not found (404).
            $this->clientError(_('No such page.'), 404);
        }

        return true;
    }

    /**
     * Title of the page
     *
     * @return page title, including page number if over 1
     */
    function title()
    {
        if ($this->page > 1) {
            // TRANS: Title for all public timeline pages but the first.
            // TRANS: %d is the page number.
            return sprintf(_('Public timeline, page %d'), $this->page);
        } else {
            // TRANS: Title for the first public timeline page.
            return _('Public timeline');
        }
    }

    function extraHead()
    {
        parent::extraHead();
        $rsd = common_local_url('rsd');

        // RSD, http://tales.phrasewise.com/rfc/rsd

        $this->element('link', array('rel' => 'EditURI',
                                     'type' => 'application/rsd+xml',
                                     'href' => $rsd));

        if ($this->page != 1) {
            $this->element('link', array('rel' => 'canonical',
                                         'href' => common_local_url('public')));
        }
    }

    /**
     * Output <head> elements for RSS and Atom feeds
     *
     * @return void
     */
    function getFeeds()
    {
        return array(new Feed(Feed::JSON,
                              common_local_url('ApiTimelinePublic',
                                               array('format' => 'as')),
                              // TRANS: Link description for public timeline feed.
                              _('Public Timeline Feed (Activity Streams JSON)')),
                    new Feed(Feed::RSS1, common_local_url('publicrss'),
                              // TRANS: Link description for public timeline feed.
                              _('Public Timeline Feed (RSS 1.0)')),
                     new Feed(Feed::RSS2,
                              common_local_url('ApiTimelinePublic',
                                               array('format' => 'rss')),
                              // TRANS: Link description for public timeline feed.
                              _('Public Timeline Feed (RSS 2.0)')),
                     new Feed(Feed::ATOM,
                              common_local_url('ApiTimelinePublic',
                                               array('format' => 'atom')),
                              // TRANS: Link description for public timeline feed.
                              _('Public Timeline Feed (Atom)')));
    }

    function showEmptyList()
    {
        // TRANS: Text displayed for public feed when there are no public notices.
        $message = _('This is the public timeline for %%site.name%% but no one has posted anything yet.') . ' ';

        if (common_logged_in()) {
            // TRANS: Additional text displayed for public feed when there are no public notices for a logged in user.
            $message .= _('Be the first to post!');
        }
        else {
            if (! (common_config('site','closed') || common_config('site','inviteonly'))) {
                // TRANS: Additional text displayed for public feed when there are no public notices for a not logged in user.
                $message .= _('Why not [register an account](%%action.register%%) and be the first to post!');
            }
        }

        $this->elementStart('div', 'guide');
        $this->raw(common_markup_to_html($message));
        $this->elementEnd('div');
    }

    /**
     * Fill the content area
     *
     * Shows a list of the notices in the public stream, with some pagination
     * controls.
     *
     * @return void
     */
    function showContent()
    {
        if ($this->scoped instanceof Profile && $this->scoped->isLocal() && $this->scoped->getUser()->streamModeOnly()) {
            $nl = new PrimaryNoticeList($this->notice, $this, array('show_n'=>NOTICES_PER_PAGE));
        } else {
            $nl = new ThreadedNoticeList($this->notice, $this, $this->scoped);
        }

        $cnt = $nl->show();

        if ($cnt == 0) {
            $this->showEmptyList();
        }

        $this->pagination($this->page > 1, $cnt > NOTICES_PER_PAGE,
                          $this->page, $this->action);
    }

    function showAnonymousMessage()
    {
        if (! (common_config('site','closed') || common_config('site','inviteonly'))) {
            // TRANS: Message for not logged in users at an invite-only site trying to view the public feed of notices.
            // TRANS: This message contains Markdown links. Please mind the formatting.
            $m = _('This is %%site.name%%, a [micro-blogging](http://en.wikipedia.org/wiki/Micro-blogging) service ' .
                   'based on the Free Software [StatusNet](http://status.net/) tool. ' .
                   '[Join now](%%action.register%%) to share notices about yourself with friends, family, and colleagues! ' .
                   '([Read more](%%doc.help%%))');
        } else {
            // TRANS: Message for not logged in users at a closed site trying to view the public feed of notices.
            // TRANS: This message contains Markdown links. Please mind the formatting.
            $m = _('This is %%site.name%%, a [micro-blogging](http://en.wikipedia.org/wiki/Micro-blogging) service ' .
                   'based on the Free Software [StatusNet](http://status.net/) tool.');
        }
        $this->elementStart('div', array('id' => 'anon_notice'));
        $this->raw(common_markup_to_html($m));
        $this->elementEnd('div');
    }
}


code:
<?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/>.
 */

if (!defined('STATUSNET') && !defined('LACONICA')) {
    exit(1);
}

/**
 * Queue handler for pushing new notices to local subscribers using SMS.
 */
class SmsQueueHandler extends QueueHandler
{
    function transport()
    {
        return 'sms';
    }

    function handle($notice)
    {
    	require_once(INSTALLDIR.'/lib/mail.php');
        return mail_broadcast_notice_sms($notice);
    }
}