code:
<?php
// This file is part of GNU social - https://www.gnu.org/software/social
//
// GNU social 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.
//
// GNU social 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 GNU social.  If not, see <http://www.gnu.org/licenses/>.

/**
 * Database schema for MariaDB
 *
 * @category  Database
 * @package   GNUsocial
 * @author    Evan Prodromou <evan@status.net>
 * @copyright 2019 Free Software Foundation, Inc http://www.fsf.org
 * @license   https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
 */

defined('GNUSOCIAL') || die();

/**
 * Class representing the database schema for MariaDB
 *
 * A class representing the database schema. Can be used to
 * manipulate the schema -- especially for plugins and upgrade
 * utilities.
 *
 * @copyright 2019 Free Software Foundation, Inc http://www.fsf.org
 * @license   https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
 */
class MysqlSchema extends Schema
{
    public static $_single = null;

    /**
     * Main public entry point. Use this to get
     * the singleton object.
     *
     * @param object|null $conn
     * @param string|null dummy param
     * @return Schema the (single) Schema object
     */
    public static function get($conn = null, $_ = 'mysql')
    {
        if (empty(self::$_single)) {
            self::$_single = new Schema($conn, 'mysql');
        }
        return self::$_single;
    }

    /**
     * Returns a TableDef object for the table
     * in the schema with the given name.
     *
     * Throws an exception if the table is not found.
     *
     * @param string $table Name of the table to get
     *
     * @return array of tabledef for that table.
     * @throws PEAR_Exception
     * @throws SchemaTableMissingException
     */
    public function getTableDef($table)
    {
        $def = [];
        $hasKeys = false;

        // Pull column data from INFORMATION_SCHEMA
        $columns = $this->fetchMetaInfo($table, 'COLUMNS', 'ORDINAL_POSITION');
        if (count($columns) == 0) {
            throw new SchemaTableMissingException("No such table: $table");
        }

        foreach ($columns as $row) {
            $name = $row['COLUMN_NAME'];
            $field = [];

            // warning -- 'unsigned' attr on numbers isn't given in DATA_TYPE and friends.
            // It is stuck in on COLUMN_TYPE though (eg 'bigint(20) unsigned')
            $field['type'] = $type = $row['DATA_TYPE'];

            if ($type == 'char' || $type == 'varchar') {
                if ($row['CHARACTER_MAXIMUM_LENGTH'] !== null) {
                    $field['length'] = intval($row['CHARACTER_MAXIMUM_LENGTH']);
                }
            }
            if ($type == 'decimal') {
                // Other int types may report these values, but they're irrelevant.
                // Just ignore them!
                if ($row['NUMERIC_PRECISION'] !== null) {
                    $field['precision'] = intval($row['NUMERIC_PRECISION']);
                }
                if ($row['NUMERIC_SCALE'] !== null) {
                    $field['scale'] = intval($row['NUMERIC_SCALE']);
                }
            }
            if ($row['IS_NULLABLE'] == 'NO') {
                $field['not null'] = true;
            }
            if ($row['COLUMN_DEFAULT'] !== null) {
                // Hack for timestamp columns
                if ($row['COLUMN_DEFAULT'] === 'current_timestamp()') {
                    // skip timestamp columns as they get a CURRENT_TIMESTAMP default implicitly
                    if ($type !== 'timestamp') {
                        $field['default'] = 'CURRENT_TIMESTAMP';
                    }
                } elseif ($this->isNumericType($type)) {
                    $field['default'] = intval($row['COLUMN_DEFAULT']);
                } else {
                    $field['default'] = $row['COLUMN_DEFAULT'];
                }
            }
            if ($row['COLUMN_KEY'] !== null) {
                // We'll need to look up key info...
                $hasKeys = true;
            }
            if ($row['COLUMN_COMMENT'] !== null && $row['COLUMN_COMMENT'] != '') {
                $field['description'] = $row['COLUMN_COMMENT'];
            }

            $extra = $row['EXTRA'];
            if ($extra) {
                if (preg_match('/(^|\s)auto_increment(\s|$)/i', $extra)) {
                    $field['auto_increment'] = true;
                }
                // $row['EXTRA'] may contain 'on update CURRENT_TIMESTAMP'
                // ^ ...... how to specify?
            }

            /* @fixme check against defaults?
            if ($row['CHARACTER_SET_NAME'] !== null) {
                $def['charset'] = $row['CHARACTER_SET_NAME'];
                $def['collate'] = $row['COLLATION_NAME'];
            }*/

            $def['fields'][$name] = $field;
        }

        if ($hasKeys) {
            // INFORMATION_SCHEMA's CONSTRAINTS and KEY_COLUMN_USAGE tables give
            // good info on primary and unique keys but don't list ANY info on
            // multi-value keys, which is lame-o. Sigh.
            $keyColumns = $this->fetchMetaInfo($table, 'KEY_COLUMN_USAGE', 'CONSTRAINT_NAME, ORDINAL_POSITION');
            $keys = [];
            $fkeys = [];

            foreach ($keyColumns as $row) {
                $keyName = $row['CONSTRAINT_NAME'];
                $keyCol = $row['COLUMN_NAME'];
                if (!isset($keys[$keyName])) {
                    $keys[$keyName] = [];
                }
                $keys[$keyName][] = $keyCol;
                if (!is_null($row['REFERENCED_TABLE_NAME'])) {
                    $fkeys[] = $keyName;
                }
            }

            foreach ($keys as $keyName => $cols) {
                if ($keyName === 'PRIMARY') {
                    $def['primary key'] = $cols;
                } elseif (in_array($keyName, $fkeys)) {
                    $fkey = $this->fetchForeignKeyInfo($table, $keyName);
                    $colMap = array_combine($cols, $fkey['cols']);
                    $def['foreign keys'][$keyName] = [$fkey['table_name'], $colMap];
                } else {
                    $def['unique keys'][$keyName] = $cols;
                }
            }

            $indexInfo = $this->fetchIndexInfo($table);

            foreach ($indexInfo as $row) {
                $keyName = $row['key_name'];
                $cols = $row['cols'];

                if ($row['key_type'] === 'FULLTEXT') {
                    $def['fulltext indexes'][$keyName] = $cols;
                } else {
                    $def['indexes'][$keyName] = $cols;
                }
            }
        }
        return $def;
    }

    /**
     * Pull the given table properties from INFORMATION_SCHEMA.
     * Most of the good stuff is MySQL extensions.
     *
     * @param $table
     * @param $props
     * @return array
     * @throws PEAR_Exception
     * @throws SchemaTableMissingException
     */
    public function getTableProperties($table, $props)
    {
        $data = $this->fetchMetaInfo($table, 'TABLES');
        if ($data) {
            return $data[0];
        } else {
            throw new SchemaTableMissingException("No such table: $table");
        }
    }

    /**
     * Pull some INFORMATION.SCHEMA data for the given table.
     *
     * @param string $table
     * @param $infoTable
     * @param null $orderBy
     * @return array of arrays
     * @throws PEAR_Exception
     */
    public function fetchMetaInfo($table, $infoTable, $orderBy = null)
    {
        $query = "SELECT * FROM INFORMATION_SCHEMA.%s " .
            "WHERE TABLE_SCHEMA='%s' AND TABLE_NAME='%s'";
        $schema = $this->conn->dsn['database'];
        $sql = sprintf($query, $infoTable, $schema, $table);
        if ($orderBy) {
            $sql .= ' ORDER BY ' . $orderBy;
        }
        return $this->fetchQueryData($sql);
    }

    /**
     * Pull index and keys information for the given table.
     *
     * @param string $table
     * @return array of arrays
     * @throws PEAR_Exception
     */
    public function fetchIndexInfo(string $table): array
    {
        $query = 'SELECT INDEX_NAME AS `key_name`, INDEX_TYPE AS `key_type`, COLUMN_NAME AS `col` ' .
            'FROM INFORMATION_SCHEMA.STATISTICS ' .
            'WHERE TABLE_SCHEMA = \'%s\' AND TABLE_NAME = \'%s\' AND NON_UNIQUE = TRUE ' .
            'AND INDEX_NAME NOT IN (SELECT CONSTRAINT_NAME FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE WHERE REFERENCED_TABLE_NAME IS NOT NULL) ' .
            'ORDER BY SEQ_IN_INDEX';
        $schema = $this->conn->dsn['database'];
        $sql = sprintf($query, $schema, $table);
        $data = $this->fetchQueryData($sql);

        $rows = [];
        foreach ($data as $row) {
            $name = $row['key_name'];
            if (isset($rows[$name])) {
                $rows[$name]['cols'][] = $row['col'];
            } else {
                $row['cols'] = [$row['col']];
                unset($row['col']);
                $rows[$name] = $row;
            }
        }
        return array_values($rows);
    }

    /**
     * @param string $table
     * @param string $constraint_name
     * @return array array of rows with keys: table_name, cols (array of strings)
     * @throws PEAR_Exception
     */
    public function fetchForeignKeyInfo(string $table, string $constraint_name): array
    {
        $query = 'SELECT REFERENCED_TABLE_NAME AS `table_name`, REFERENCED_COLUMN_NAME AS `col` ' .
            'FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE ' .
            'WHERE TABLE_SCHEMA = \'%s\' AND TABLE_NAME = \'%s\' AND CONSTRAINT_NAME = \'%s\' ' .
            'AND REFERENCED_TABLE_SCHEMA IS NOT NULL ' .
            'ORDER BY POSITION_IN_UNIQUE_CONSTRAINT';
        $schema = $this->conn->dsn['database'];
        $sql = sprintf($query, $schema, $table, $constraint_name);
        $data = $this->fetchQueryData($sql);
        if (count($data) < 1) {
            throw new Exception('Could not find foreign key ' . $constraint_name . ' on table ' . $table);
        }

        $info = [
            'table_name' => $data[0]['table_name'],
            'cols'       => [],
        ];
        foreach ($data as $row) {
            $info['cols'][] = $row['col'];
        }
        return $info;
    }

    /**
     * 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
     */
    public function appendCreateFulltextIndex(array &$statements, $table, $name, array $def)
    {
        $statements[] = "CREATE FULLTEXT INDEX $name ON $table " . $this->buildIndexList($def);
    }

    /**
     * Close out a 'create table' SQL statement.
     *
     * @param string $name
     * @param array $def
     * @return string;
     *
     */
    public function endCreateTable($name, array $def)
    {
        $engine = $this->preferredEngine($def);
        return ") ENGINE=$engine CHARACTER SET utf8mb4 COLLATE utf8mb4_bin";
    }

    public function preferredEngine($def)
    {
        /* MyISAM is no longer required for fulltext indexes, fortunately
        if (!empty($def['fulltext indexes'])) {
            return 'MyISAM';
        }
        */
        return 'InnoDB';
    }

    /**
     * Get the unique index key name for a given column on this table
     * @param $tableName
     * @param $columnName
     * @return string
     */
    public function _uniqueKey($tableName, $columnName)
    {
        return $this->_key($tableName, $columnName);
    }

    /**
     * Get the index key name for a given column on this table
     * @param $tableName
     * @param $columnName
     * @return string
     */
    public function _key($tableName, $columnName)
    {
        return "{$tableName}_{$columnName}_idx";
    }

    /**
     * MySQL doesn't take 'DROP CONSTRAINT', need to treat primary keys as
     * if they were indexes here, but can use 'PRIMARY KEY' special name.
     *
     * @param array $phrase
     */
    public function appendAlterDropPrimary(array &$phrase, string $tableName)
    {
        $phrase[] = 'DROP PRIMARY KEY';
    }

    /**
     * MySQL doesn't take 'DROP CONSTRAINT', need to treat unique keys as
     * if they were indexes here.
     *
     * @param array $phrase
     * @param string $keyName MySQL
     */
    public function appendAlterDropUnique(array &$phrase, $keyName)
    {
        $phrase[] = 'DROP INDEX ' . $keyName;
    }

    /**
     * Throw some table metadata onto the ALTER TABLE if we have a mismatch
     * in expected type, collation.
     * @param array $phrase
     * @param $tableName
     * @param array $def
     * @throws Exception
     */
    public function appendAlterExtras(array &$phrase, $tableName, array $def)
    {
        // Check for table properties: make sure we're using a sane
        // engine type and charset/collation.
        // @fixme make the default engine configurable?
        $oldProps = $this->getTableProperties($tableName, ['ENGINE', 'TABLE_COLLATION']);
        $engine = $this->preferredEngine($def);
        if (strtolower($oldProps['ENGINE']) != strtolower($engine)) {
            $phrase[] = "ENGINE=$engine";
        }
        if (strtolower($oldProps['TABLE_COLLATION']) != 'utf8mb4_bin') {
            $phrase[] = 'CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_bin';
            $phrase[] = 'DEFAULT CHARACTER SET = utf8mb4';
            $phrase[] = 'DEFAULT COLLATE = utf8mb4_bin';
        }
    }

    /**
     * Is this column a string type?
     * @param array $cd
     * @return bool
     */
    private function _isString(array $cd)
    {
        $strings = ['char', 'varchar', 'text'];
        return in_array(strtolower($cd['type']), $strings);
    }

    /**
     * Return the proper SQL for creating or
     * altering a column.
     *
     * Appropriate for use in CREATE TABLE or
     * ALTER TABLE statements.
     *
     * @param string $name column name to create
     * @param array $cd column to create
     *
     * @return string correct SQL for that column
     */
    public function columnSql(string $name, array $cd)
    {
        $line = [];
        $line[] = parent::columnSql($name, $cd);

        // This'll have been added from our transform of 'serial' type
        if (!empty($cd['auto_increment'])) {
            $line[] = 'auto_increment';
        }

        if (!empty($cd['description'])) {
            $line[] = 'comment';
            $line[] = $this->quoteValue($cd['description']);
        }

        return implode(' ', $line);
    }

    public function mapType($column)
    {
        $map = [
            'integer' => 'int',
            'bool'    => 'tinyint',
            'numeric' => 'decimal',
        ];

        $type = $column['type'];
        if (isset($map[$type])) {
            $type = $map[$type];
        }

        if (!empty($column['size'])) {
            $size = $column['size'];
            if ($type == 'int' &&
                in_array($size, ['tiny', 'small', 'medium', 'big'])) {
                $type = $size . $type;
            } elseif ($type == 'float' && $size == 'big') {
                $type = 'double';
            } elseif (in_array($type, ['blob', 'text']) &&
                in_array($size, ['tiny', 'medium', 'long'])) {
                $type = $size . $type;
            }
        }

        return $type;
    }

    public function typeAndSize(string $name, array $column)
    {
        if ($column['type'] === 'enum') {
            foreach ($column['enum'] as &$val) {
                $vals[] = "'" . $val . "'";
            }
            return 'enum(' . implode(',', $vals) . ')';
        } elseif ($this->_isString($column)) {
            $col = parent::typeAndSize($name, $column);
            if (!empty($column['charset'])) {
                $col .= ' CHARSET ' . $column['charset'];
            }
            if (!empty($column['collate'])) {
                $col .= ' COLLATE ' . $column['collate'];
            }
            return $col;
        } else {
            return parent::typeAndSize($name, $column);
        }
    }

    /**
     * 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
     * @return array
     */
    public function filterDef(array $tableDef)
    {
        $version = $this->conn->getVersion();
        foreach ($tableDef['fields'] as $name => &$col) {
            if ($col['type'] == 'serial') {
                $col['type'] = 'int';
                $col['auto_increment'] = true;
            }

            $col['type'] = $this->mapType($col);
            unset($col['size']);
        }
        if (!common_config('db', 'mysql_foreign_keys')) {
            unset($tableDef['foreign keys']);
        }
        return $tableDef;
    }
}


code:
<?php
// This file is part of GNU social - https://www.gnu.org/software/social
//
// GNU social 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.
//
// GNU social 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 GNU social.  If not, see <http://www.gnu.org/licenses/>.

/**
 * Database schema for PostgreSQL
 *
 * @category  Database
 * @package   GNUsocial
 * @author    Evan Prodromou <evan@status.net>
 * @author    Brenda Wallace <shiny@cpan.org>
 * @author    Brion Vibber <brion@status.net>
 * @copyright 2019 Free Software Foundation, Inc http://www.fsf.org
 * @license   https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
 */

defined('GNUSOCIAL') || die();

/**
 * Class representing the database schema for PostgreSQL
 *
 * A class representing the database schema. Can be used to
 * manipulate the schema -- especially for plugins and upgrade
 * utilities.
 *
 * @copyright 2019 Free Software Foundation, Inc http://www.fsf.org
 * @license   https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
 */
class PgsqlSchema extends Schema
{
    public static $_single = null;

    /**
     * Main public entry point. Use this to get
     * the singleton object.
     *
     * @param object|null $conn
     * @param string|null dummy param
     * @return Schema the (single) Schema object
     */
    public static function get($conn = null, $_ = 'pgsql')
    {
        if (empty(self::$_single)) {
            self::$_single = new Schema($conn, 'pgsql');
        }
        return self::$_single;
    }

    /**
     * Returns a table definition array for the table
     * in the schema with the given name.
     *
     * Throws an exception if the table is not found.
     *
     * @param string $table Name of the table to get
     *
     * @return array tabledef for that table.
     * @throws SchemaTableMissingException
     */
    public function getTableDef($table)
    {
        $def = [];
        $hasKeys = false;

        // Pull column data from INFORMATION_SCHEMA
        $columns = $this->fetchMetaInfo($table, 'columns', 'ordinal_position');
        if (count($columns) == 0) {
            throw new SchemaTableMissingException("No such table: $table");
        }

        // We'll need to match up fields by ordinal reference
        $orderedFields = [];

        foreach ($columns as $row) {
            $name = $row['column_name'];
            $orderedFields[$row['ordinal_position']] = $name;

            $field = [];
            $field['type'] = $type = $row['udt_name'];

            if (in_array($type, ['char', 'bpchar', 'varchar'])) {
                if ($row['character_maximum_length'] !== null) {
                    $field['length'] = intval($row['character_maximum_length']);
                }
            }
            if ($type == 'numeric') {
                // Other int types may report these values, but they're irrelevant.
                // Just ignore them!
                if ($row['numeric_precision'] !== null) {
                    $field['precision'] = intval($row['numeric_precision']);
                }
                if ($row['numeric_scale'] !== null) {
                    $field['scale'] = intval($row['numeric_scale']);
                }
            }
            if ($row['is_nullable'] == 'NO') {
                $field['not null'] = true;
            }
            if ($row['column_default'] !== null) {
                $field['default'] = $row['column_default'];
                if ($this->isNumericType($type)) {
                    $field['default'] = intval($field['default']);
                }
            }

            $def['fields'][$name] = $field;
        }

        // Pulling index info from pg_class & pg_index
        // This can give us primary & unique key info, but not foreign key constraints
        // so we exclude them and pick them up later.
        $indexInfo = $this->fetchIndexInfo($table);

        foreach ($indexInfo as $row) {
            $keyName = $row['key_name'];

            // Dig the column references out!
            //
            // These are inconvenient arrays with partial references to the
            // pg_att table, but since we've already fetched up the column
            // info on the current table, we can look those up locally.
            $cols = [];
            $colPositions = explode(' ', $row['indkey']);
            foreach ($colPositions as $ord) {
                if ($ord == 0) {
                    $cols[] = 'FUNCTION'; // @fixme
                } else {
                    $cols[] = $orderedFields[$ord];
                }
            }

            $def['indexes'][$keyName] = $cols;
        }

        // Pull constraint data from INFORMATION_SCHEMA:
        // Primary key, unique keys, foreign keys
        $keyColumns = $this->fetchMetaInfo($table, 'key_column_usage', 'constraint_name,ordinal_position');
        $keys = [];

        foreach ($keyColumns as $row) {
            $keyName = $row['constraint_name'];
            $keyCol = $row['column_name'];
            if (!isset($keys[$keyName])) {
                $keys[$keyName] = [];
            }
            $keys[$keyName][] = $keyCol;
        }

        foreach ($keys as $keyName => $cols) {
            // name hack -- is this reliable?
            if ($keyName == "{$table}_pkey") {
                $def['primary key'] = $cols;
            } elseif (preg_match("/^{$table}_(.*)_fkey$/", $keyName, $matches)) {
                $fkey = $this->fetchForeignKeyInfo($table, $keyName);
                $colMap = array_combine($cols, $fkey['col_names']);
                $def['foreign keys'][$keyName] = [$fkey['table_name'], $colMap];
            } else {
                $def['unique keys'][$keyName] = $cols;
            }
        }
        return $def;
    }

    /**
     * Pull some INFORMATION.SCHEMA data for the given table.
     *
     * @param string $table
     * @param $infoTable
     * @param null $orderBy
     * @return array of arrays
     * @throws PEAR_Exception
     */
    public function fetchMetaInfo($table, $infoTable, $orderBy = null)
    {
        $query = "SELECT * FROM information_schema.%s " .
            "WHERE table_name='%s'";
        $sql = sprintf($query, $infoTable, $table);
        if ($orderBy) {
            $sql .= ' ORDER BY ' . $orderBy;
        }
        return $this->fetchQueryData($sql);
    }

    /**
     * Pull some PG-specific index info
     * @param string $table
     * @return array of arrays
     * @throws PEAR_Exception
     */
    public function fetchIndexInfo(string $table): array
    {
        $query = 'SELECT indexname AS key_name, indexdef AS key_def, pg_index.* ' .
            'FROM pg_index INNER JOIN pg_indexes ON pg_index.indexrelid = CAST(pg_indexes.indexname AS regclass) ' .
            'WHERE tablename = \'%s\' AND indisprimary = FALSE AND indisunique = FALSE ' .
            'ORDER BY indrelid, indexrelid';
        $sql = sprintf($query, $table);
        return $this->fetchQueryData($sql);
    }

    /**
     * @param string $table
     * @param string $constraint_name
     * @return array array of rows with keys: table_name, col_names (array of strings)
     * @throws PEAR_Exception
     */
    public function fetchForeignKeyInfo(string $table, string $constraint_name): array
    {
        // In a sane world, it'd be easier to query the column names directly.
        // But it's pretty hard to work with arrays such as col_indexes in direct SQL here.
        $query = 'SELECT ' .
            '(SELECT relname FROM pg_class WHERE oid = confrelid) AS table_name, ' .
            'confrelid AS table_id, ' .
            '(SELECT indkey FROM pg_index WHERE indexrelid = conindid) AS col_indices ' .
            'FROM pg_constraint ' .
            'WHERE conrelid = CAST(\'%s\' AS regclass) AND conname = \'%s\' AND contype = \'f\'';
        $sql = sprintf($query, $table, $constraint_name);
        $data = $this->fetchQueryData($sql);
        if (count($data) < 1) {
            throw new Exception('Could not find foreign key ' . $constraint_name . ' on table ' . $table);
        }

        $row = $data[0];
        return [
            'table_name' => $row['table_name'],
            'col_names' => $this->getTableColumnNames($row['table_id'], $row['col_indices'])
        ];
    }

    /**
     *
     * @param int $table_id
     * @param array $col_indexes
     * @return array of strings
     * @throws PEAR_Exception
     */
    public function getTableColumnNames($table_id, $col_indexes)
    {
        $indexes = array_map('intval', explode(' ', $col_indexes));
        $query = 'SELECT attnum AS col_index, attname AS col_name ' .
            'FROM pg_attribute where attrelid=%d ' .
            'AND attnum IN (%s)';
        $sql = sprintf($query, $table_id, implode(',', $indexes));
        $data = $this->fetchQueryData($sql);

        $byId = [];
        foreach ($data as $row) {
            $byId[$row['col_index']] = $row['col_name'];
        }

        $out = [];
        foreach ($indexes as $id) {
            $out[] = $byId[$id];
        }
        return $out;
    }

    /**
     * Return the proper SQL for creating or
     * altering a column.
     *
     * Appropriate for use in CREATE TABLE or
     * ALTER TABLE statements.
     *
     * @param string $name column name to create
     * @param array $cd column to create
     *
     * @return string correct SQL for that column
     */
    public function columnSql(string $name, array $cd)
    {
        $line = [];
        $line[] = parent::columnSql($name, $cd);

        /*
        if ($table['foreign keys'][$name]) {
            foreach ($table['foreign keys'][$name] as $foreignTable => $foreignColumn) {
                $line[] = 'references';
                $line[] = $this->quoteIdentifier($foreignTable);
                $line[] = '(' . $this->quoteIdentifier($foreignColumn) . ')';
            }
        }
        */

        // This'll have been added from our transform of 'serial' type
        if (!empty($cd['auto_increment'])) {
            $line[] = 'GENERATED BY DEFAULT AS IDENTITY';
        } elseif (!empty($cd['enum'])) {
            foreach ($cd['enum'] as &$val) {
                $vals[] = "'" . $val . "'";
            }
            $line[] = 'CHECK (' . $name . ' IN (' . implode(',', $vals) . '))';
        }

        return implode(' ', $line);
    }

    /**
     * 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
     */
    public function appendAlterModifyColumn(array &$phrase, $columnName, array $old, array $cd)
    {
        $prefix = 'ALTER COLUMN ' . $this->quoteIdentifier($columnName) . ' ';

        $oldType = $this->typeAndSize($columnName, $old);
        $newType = $this->typeAndSize($columnName, $cd);
        if ($oldType != $newType) {
            $phrase[] = $prefix . 'TYPE ' . $newType;
        }

        if (!empty($old['not null']) && empty($cd['not null'])) {
            $phrase[] = $prefix . 'DROP NOT NULL';
        } elseif (empty($old['not null']) && !empty($cd['not null'])) {
            $phrase[] = $prefix . 'SET NOT NULL';
        }

        if (isset($old['default']) && !isset($cd['default'])) {
            $phrase[] = $prefix . 'DROP DEFAULT';
        } elseif (!isset($old['default']) && isset($cd['default'])) {
            $phrase[] = $prefix . 'SET DEFAULT ' . $this->quoteDefaultValue($cd);
        }
    }

    public function appendAlterDropPrimary(array &$phrase, string $tableName)
    {
        // name hack -- is this reliable?
        $phrase[] = 'DROP CONSTRAINT ' . $this->quoteIdentifier($tableName . '_pkey');
    }

    /**
     * Append an SQL statement to drop an index from a table.
     * Note that in PostgreSQL, index names are DB-unique.
     *
     * @param array $statements
     * @param string $table
     * @param string $name
     */
    public function appendDropIndex(array &$statements, $table, $name)
    {
        $statements[] = "DROP INDEX $name";
    }

    public function mapType($column)
    {
        $map = [
            'integer'  => 'int',
            'char'     => 'bpchar',
            'datetime' => 'timestamp',
            'blob'     => 'bytea',
            'enum'     => 'text',
        ];

        $type = $column['type'];
        if (isset($map[$type])) {
            $type = $map[$type];
        }

        $size = $column['size'] ?? null;
        if ($type === 'int') {
            if (in_array($size, ['tiny', 'small'])) {
                $type = 'int2';
            } elseif ($size === 'big') {
                $type = 'int8';
            } else {
                $type = 'int4';
            }
        } elseif ($type === 'float') {
            $type = ($size !== 'big') ? 'float4' : 'float8';
        }

        return $type;
    }

    /**
     * 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
     * @return array
     */
    public function filterDef(array $tableDef)
    {
        foreach ($tableDef['fields'] as $name => &$col) {
            // No convenient support for field descriptions
            unset($col['description']);

            switch ($col['type']) {
                case 'serial':
                    $col['type'] = 'int';
                    $col['auto_increment'] = true;
                    break;
                case 'datetime':
                    // Replace archaic MySQL-specific zero-dates with NULL
                    if (($col['default'] ?? null) === '0000-00-00 00:00:00') {
                        $col['default'] = null;
                        $col['not null'] = false;
                    }
                    break;
                case 'timestamp':
                    // In MariaDB: If the column does not permit NULL values,
                    // assigning NULL (or not referencing the column at all
                    // when inserting) will set the column to CURRENT_TIMESTAMP
                    // FIXME: ON UPDATE CURRENT_TIMESTAMP
                    if ($col['not null'] && !isset($col['default'])) {
                        $col['default'] = 'CURRENT_TIMESTAMP';
                    }
                    break;
            }

            $col['type'] = $this->mapType($col);
            unset($col['size']);
        }

        if (!empty($tableDef['primary key'])) {
            $tableDef['primary key'] = $this->filterKeyDef($tableDef['primary key']);
        }
        if (!empty($tableDef['unique keys'])) {
            foreach ($tableDef['unique keys'] as $i => $def) {
                $tableDef['unique keys'][$i] = $this->filterKeyDef($def);
            }
        }
        return $tableDef;
    }

    /**
     * Filter the given key/index definition to match features available
     * in this database.
     *
     * @param array $def
     * @return array
     */
    public function filterKeyDef(array $def)
    {
        // PostgreSQL doesn't like prefix lengths specified on keys...?
        foreach ($def as $i => $item) {
            if (is_array($item)) {
                $def[$i] = $item[0];
            }
        }
        return $def;
    }
}

repo_name: suraj/sloth

license: mit


code:
<?php
// This file is part of GNU social - https://www.gnu.org/software/social
//
// GNU social 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.
//
// GNU social 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 GNU social.  If not, see <http://www.gnu.org/licenses/>.

/**
 * Database schema
 *
 * @category  Database
 * @package   GNUsocial
 * @author    Evan Prodromou <evan@status.net>
 * @author    Brion Vibber <brion@status.net>
 * @copyright 2019 Free Software Foundation, Inc http://www.fsf.org
 * @license   https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
 */

defined('GNUSOCIAL') || die();

/**
 * Class representing the database schema
 *
 * A class representing the database schema. Can be used to
 * manipulate the schema -- especially for plugins and upgrade
 * utilities.
 *
 * @copyright 2019 Free Software Foundation, Inc http://www.fsf.org
 * @license   https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
 */
class Schema
{
    public static $_static = null;
    protected $conn = null;

    /**
     * Constructor. Only run once for singleton object.
     * @param null $conn
     */
    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.
     *
     * @param object|null $conn
     * @param string|null Force a database type (necessary for installation purposes in which we don't have a config.php)
     * @return Schema the Schema object for the connection
     */
    public static function get($conn = null, $dbtype = null)
    {
        if (is_null($conn)) {
            $key = 'default';
        } else {
            $key = md5(serialize($conn->dsn));
        }

        if (is_null($dbtype)) {
            $dbtype = common_config('db', 'type');
        }
        if (empty(self::$_static[$key])) {
            $schemaClass = ucfirst($dbtype) . '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 bool success flag
     * @throws PEAR_Exception
     */
    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 array success flag
     * @throws Exception
     */
    public function buildCreateTable($name, $def)
    {
        $def = $this->validateDef($name, $def);
        $def = $this->filterDef($def);
        $sql = [];

        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 = [];
        $statements[] = $this->startCreateTable($name, $def) . "\n" .
            implode(",\n", $sql) . "\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
     * @return string
     */
    public 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
     */
    public 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
     */
    public function appendColumnDef(array &$sql, string $name, array $def)
    {
        $sql[] = $name . ' ' . $this->columnSql($name, $def);
    }

    /**
     * Append an SQL fragment with a constraint definition for a primary
     * key in a CREATE TABLE statement.
     *
     * @param array $sql
     * @param array $def
     */
    public 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
     */
    public 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
     * @throws Exception
     */
    public 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 ' . $this->quoteIdentifier($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
     */
    public function appendCreateIndex(array &$statements, $table, $name, array $def)
    {
        $statements[] = 'CREATE INDEX ' . $name . ' ON ' .
                        $this->quoteIdentifier($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
     * @throws Exception
     */
    public 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
     */
    public function appendDropIndex(array &$statements, $table, $name)
    {
        $statements[] = "DROP INDEX $name ON " . $this->quoteIdentifier($table);
    }

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

    public 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 bool success flag
     * @throws PEAR_Exception
     */
    public function dropTable($name)
    {
        global $_PEAR;

        $res = $this->conn->query('DROP TABLE ' . $this->quoteIdentifier($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 bool success flag
     * @throws PEAR_Exception
     */
    public function createIndex($table, $columnNames, $name = null)
    {
        global $_PEAR;

        $qry = [];

        if (!is_array($columnNames)) {
            $columnNames = [$columnNames];
        }

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

        $this->appendCreateIndex($qry, $table, $name, $columnNames);

        $res = $this->conn->query(implode('; ', $qry));

        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 bool success flag
     * @throws PEAR_Exception
     */
    public function dropIndex($table, $name)
    {
        global $_PEAR;

        $res = $this->conn->query(
            'ALTER TABLE ' . $this->quoteIdentifier($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 bool success flag
     * @throws PEAR_Exception
     */
    public function addColumn($table, $columndef)
    {
        global $_PEAR;

        $sql = 'ALTER TABLE ' . $this->quoteIdentifier($table) .
               ' ADD COLUMN ' . $this->columnSql($name, $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 bool success flag
     * @throws PEAR_Exception
     */
    public function modifyColumn($table, $columndef)
    {
        global $_PEAR;

        $sql = 'ALTER TABLE ' . $this->quoteIdentifier($table) .
               ' MODIFY COLUMN ' . $this->columnSql($name, $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 bool success flag
     * @throws PEAR_Exception
     */
    public function dropColumn($table, $columnName)
    {
        global $_PEAR;

        $sql = 'ALTER TABLE ' . $this->quoteIdentifier($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 bool success flag
     * @throws PEAR_Exception
     */
    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 bool success flag
     * @throws PEAR_Exception
     */
    public function runSqlSet(array $statements)
    {
        global $_PEAR;

        $ok = true;
        foreach ($statements as $sql) {
            if (defined('DEBUG_INSTALLER')) {
                echo "" . htmlspecialchars($sql) . "
\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 $def
     * @return array of SQL statements
     * @throws Exception
     */
    public 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 = [];
        $fields = $this->diffArrays($old, $def, 'fields', [$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 = [];

        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, $tableName);
        }

        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 ' . $this->quoteIdentifier($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;
    }

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

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

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

        // 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 [
            '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
     */
    public function appendAlterAddColumn(array &$phrase, string $columnName, array $cd)
    {
        $phrase[] = 'ADD COLUMN ' .
            $this->quoteIdentifier($columnName) .
            ' ' .
            $this->columnSql($columnName, $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
     */
    public function appendAlterModifyColumn(array &$phrase, string $columnName, array $old, array $cd)
    {
        $phrase[] = 'MODIFY COLUMN ' .
            $this->quoteIdentifier($columnName) .
            ' ' .
            $this->columnSql($columnName, $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
     */
    public function appendAlterDropColumn(array &$phrase, $columnName)
    {
        $phrase[] = 'DROP COLUMN ' . $this->quoteIdentifier($columnName);
    }

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

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

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

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

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

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

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

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

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

    public 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 bool
     */
    public 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 = [];

        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 string $name column name to create
     * @param array $cd column to create
     *
     * @return string correct SQL for that column
     */
    public function columnSql(string $name, array $cd)
    {
        $line = [];
        $line[] = $this->typeAndSize($name, $cd);

        if (isset($cd['default'])) {
            $line[] = 'default';
            $line[] = $this->quoteDefaultValue($cd);
        } elseif (!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
     */
    public function mapType($column)
    {
        return $column;
    }

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

        if (isset($column['precision'])) {
            $lengths[] = $column['precision'];
            if (isset($column['scale'])) {
                $lengths[] = $column['scale'];
            }
        } elseif (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 = [];
        $prefixes = [
            'tiny',
            'small',
            'medium',
            'big',
        ];
        foreach ($defs as $cd) {
            $column = [];
            $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'] = [];
                }
                $table['primary key'][] = $cd->name;
            } elseif ($cd->key === 'MUL') {
                // Individual multiple-value indexes are only per-column
                // using the old ColumnDef syntax.
                $idx = "{$tableName}_{$cd->name}_idx";
                $table['indexes'][$idx] = [$cd->name];
            } elseif ($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] = [$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
     * @return array
     */
    public 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
     */
    public 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;
    }

    public function isNumericType($type)
    {
        $type = strtolower($type);
        $known = ['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
     * @throws PEAR_Exception
     */
    protected function fetchQueryData($sql)
    {
        global $_PEAR;

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

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

        return $out;
    }

    public function renameTable(string $old_name, string $new_name) : bool
    {
        try {
            $this->getTableDef($old_name);
            try {
                $this->getTableDef($new_name);
                // New table exists, can't work
                throw new ServerException("Both table {$old_name} and {$new_name} exist. You're on your own.");
            } catch (SchemaTableMissingException $e) {
                // New table doesn't exist, carry on
            }
        } catch (SchemaTableMissingException $e) {
            // Already renamed, or no previous table, so we're done
            return true;
        }
        return $this->runSqlSet([
            'ALTER TABLE ' . $this->quoteIdentifier($old_name) .
            ' RENAME TO '  . $this->quoteIdentifier($new_name) . ';',
        ]);
    }
}

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;
    }
}


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);
}

/**
 * A class encapsulating the structure of a table.
 *
 * @category Database
 * @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 TableDef
{
    /** name of the table */
    public $name;
    /** array of ColumnDef objects for the columns. */
    public $columns;

    /**
     * Constructor.
     *
     * @param string  $name     name of the table
     * @param array   $columns  columns in the table
     */

    function __construct($name=null,$columns=null)
    {
        $this->name = $name;
        $this->columns = $columns;
    }
}


code:
<?php
/**
 * GNU social - a federating social network
 * Copyright (C) 2014, Free Software Foundation, 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); }

/**
 * Parent class for an exception when trying to do something that was
 * probably already done.
 *
 * This is a common case for example when remote sites are not up to
 * date with our database. For example subscriptions, where a remote
 * user may be unsubscribed from our user, but they request it anyway.
 *
 * This exception is usually caught in a manner that lets the execution
 * continue _as if_ the desired action did what it was supposed to do.
 *
 * @category Exception
 * @package  GNUsocial
 * @author   Mikael Nordfeldth <mmn@hethane.se>
 * @license  http://www.fsf.org/licensing/licenses/agpl-3.0.html AGPLv3
 * @link     http://gnu.io/
 */

class AlreadyFulfilledException extends ServerException
{
    public function __construct($msg=null)
    {
        if ($msg === null) {
            // TRANS: Exception text when attempting to perform something which seems already done.
            $msg = _('Trying to do something that was already done.');
        }

        parent::__construct($msg, 409);
    }
}


code:
<?php
/**
 * StatusNet - the distributed open-source microblogging tool
 * Copyright (C) 2011, StatusNet, Inc.
 *
 * An exception for authorization errors
 *
 * 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  Exception
 * @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);
}

/**
 * An exception for authorization issues
 *
 * @category  Exception
 * @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 AuthorizationException extends ClientException
{
    /**
     * Constructor
     *
     * @param string $message Message for the exception
     */
    public function __construct($message=null)
    {
        parent::__construct($message, 403);
    }
}


code:
<?php
/**
 * StatusNet, the distributed open-source microblogging tool
 *
 * class for a client 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 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 client exceptions
 *
 * Subclass of PHP Exception for user errors.
 *
 * @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 ClientException extends Exception
{
    public function __construct($message = null, $code = 400) {
        parent::__construct($message, $code);
    }

    // custom string representation of object
    public function __toString() {
        return __CLASS__ . ": [{$this->code}]: {$this->message}\n";
    }
}


code:
<?php

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

/**
 * Class for configuration exceptions
 *
 * Subclass of ServerException for when the site's configuration is malformed.
 *
 * @category Exception
 * @package  GNUsocial
 * @author   Mikael Nordfeldth <mmn@hethane.se>
 * @license  https://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
 * @link     https://gnu.io/social
 */

class ConfigException extends ServerException
{
    public function __construct($message=null) {
        parent::__construct($message, 500);
    }
}


code:
<?php
/**
 * StatusNet, the distributed open-source microblogging tool
 *
 * Class for an exception when there is something wrong with sending email
 *
 * 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   GNUsocial
 * @author    Mikael Nordfeldth <mmn@hethane.se>
 * @copyright 2016 Free Software Foundation, Inc.
 * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html AGPLv3
 * @link      http://www.gnu.org/software/social/
 */

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

class EmailException extends Exception
{
}


code:
<?php
/**
 * StatusNet, the distributed open-source microblogging tool
 *
 * Class for an exception when a database lookup returns no results
 *
 * 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   GNUsocial
 * @author    Mikael Nordfeldth <mmn@hethane.se>
 * @copyright 2013 Free Software Foundation, Inc.
 * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html AGPLv3
 * @link      http://www.gnu.org/software/social/
 */

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

class EmptyPkeyValueException extends ServerException
{
    public function __construct($called_class, $key=null)
    {
        // FIXME: translate the 'not specified' case?
        parent::__construct(sprintf(_('Empty primary key (%1$s) value was given to query for a "%2$s" object'),
                                        is_null($key) ? 'not specified' : _ve($key),
                                        $called_class));
    }
}


code:
<?php
/**
 * StatusNet, the distributed open-source microblogging tool
 *
 * Class for an exception when a database lookup returns no results
 *
 * 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   GNUsocial
 * @author    Mikael Nordfeldth <mmn@hethane.se>
 * @copyright 2013 Free Software Foundation, Inc.
 * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html AGPLv3
 * @link      http://www.gnu.org/software/social/
 */

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

class FileNotFoundException extends ServerException
{
    public $path = null;

    public function __construct($path)
    {
        $this->path = $path;
        common_debug('File not found exception for: '._ve($this->path));
        parent::__construct(_('File not found in filesystem.'), 404);
    }
}


code:
<?php

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

class FileNotStoredLocallyException extends ServerException
{
    public $file = null;

    public function __construct(File $file)
    {
        $this->file = $file;
        common_debug('Requested local URL for a file that is not stored locally with id=='._ve($this->file->getID()));
        parent::__construct(_('Requested local URL for a file that is not stored locally.'));
    }
}


code:
<?php
/**
 * StatusNet, the distributed open-source microblogging tool
 *
 * Class for an exception when the group profile is missing
 *
 * 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 2010 StatusNet, Inc.
 * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html AGPLv3
 * @link      http://status.net/
 */

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

/**
 * Class for an exception when the group profile is missing
 *
 * @category Exception
 * @package  StatusNet
 * @author   Evan Prodromou <evan@status.net>
 * @license  http://www.fsf.org/licensing/licenses/agpl-3.0.html AGPLv3
 * @link     http://status.net/
 */

class GroupNoProfileException extends NoProfileException
{
    protected $group = null;

    /**
     * constructor
     *
     * @param User_group $user User_group that's missing a profile
     */

    public function __construct(User_group $group)
    {
        $this->group = $group;

        // TRANS: Exception text shown when no profile can be found for a group.
        // TRANS: %1$s is a group nickname, $2$d is a group profile_id (number).
        $message = sprintf(_('Group "%1$s" (%2$d) has no profile record.'),
                           $group->nickname, $group->getID());

        parent::__construct($group->profile_id, $message);
    }

    /**
     * Accessor for user
     *
     * @return User_group the group that triggered this exception
     */

    public function getGroup()
    {
        return $this->group;
    }
}


code:
<?php
/**
 * StatusNet, the distributed open-source microblogging tool
 *
 * Class for an exception when a filename is invalid
 *
 * 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    Mikael Nordfeldth <mmn@hethane.se>
 * @copyright 2016 Free Software Foundation, Inc.
 * @license   https://www.fsf.org/licensing/licenses/agpl-3.0.html AGPLv3
 * @link      https://gnu.io/social
 */

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

/**
 * Class for an exception when a filename is invalid
 *
 * @category Exception
 * @package  GNUsocial
 * @author   Mikael Nordfeldth <mmn@hethane.se>
 * @license  https://www.fsf.org/licensing/licenses/agpl-3.0.html AGPLv3
 * @link     https://gnu.io/social
 */

class InvalidFilenameException extends ServerException
{
    public $filename = null;

    public function __construct($filename)
    {
        $this->filename = $filename;
        // We could log an entry here with the search parameters
        parent::__construct(_('Invalid filename.'));
    }
}


code:
<?php
/**
 * StatusNet, the distributed open-source microblogging tool
 *
 * Class for an exception when a URL is invalid
 *
 * 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    Mikael Nordfeldth <mmn@hethane.se>
 * @copyright 2013 Free Software Foundation, Inc.
 * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html AGPLv3
 * @link      http://status.net/
 */

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

/**
 * Class for an exception when a URL is invalid
 *
 * @category Exception
 * @package  GNUsocial
 * @author   Mikael Nordfeldth <mmn@hethane.se>
 * @license  http://www.fsf.org/licensing/licenses/agpl-3.0.html AGPLv3
 * @link     http://status.net/
 */

class InvalidUrlException extends ServerException
{
    public $url = null;

    public function __construct($url)
    {
        $this->url = $url;
        // We could log an entry here with the search parameters
        parent::__construct(_('Invalid URL.'));
    }
}


code:
<?php
/**
 * StatusNet, the distributed open-source microblogging tool
 *
 * class for an exception when a method is not implemented
 *
 * 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    Mikael Nordfeldth <mmn@hethane.se>
 * @copyright 2013 Free Software Foundation, Inc.
 * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html AGPLv3
 * @link      http://status.net/
 */

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

/**
 * Class for an exception when a local user is not found by certain criteria
 *
 * @category Exception
 * @package  StatusNet
 * @author   Mikael Nordfeldth <mmn@hethane.se>
 * @license  http://www.fsf.org/licensing/licenses/agpl-3.0.html AGPLv3
 * @link     http://status.net/
 */

class MethodNotImplementedException extends ServerException
{
    public function __construct($method)
    {
        parent::__construct(sprintf(_('Method %s not implemented'), $method));
    }
}


code:
<?php
/**
 * StatusNet, the distributed open-source microblogging tool
 *
 * Class for an exception when unable to retrieve or resize a profile's avatar.
 *
 * 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   GNUsocial
 * @author    Mikael Nordfeldth <mmn@hethane.se>
 * @copyright 2013 Free Software Foundation, Inc.
 * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html AGPLv3
 * @link      http://www.gnu.org/software/social/
 */

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

class NoAvatarException extends NoResultException
{
    public $target;

    public function __construct(Profile $target, Avatar $obj)
    {
        $this->target = $target;
        parent::__construct($obj);
    }
}


code:
<?php
/**
 * StatusNet, the distributed open-source microblogging tool
 *
 * Class for an exception when an HTTP request gets no response (DNS failure 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  Exception
 * @package   GNUsocial
 * @author    Mikael Nordfeldth <mmn@hethane.se>
 * @copyright 2013 Free Software Foundation, Inc.
 * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html AGPLv3
 * @link      http://www.gnu.org/software/social/
 */

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

// Can't extend HTTP_Request2_Exception since it requires an HTTP status code which we didn't get
class NoHttpResponseException extends HTTP_Request2_ConnectionException
{
    public $url;    // target URL

    public function __construct($url)
    {
        $this->url = $url;
        // We could log an entry here with the search parameters
        parent::__construct(sprintf(_('No HTTP response from URL %s.'), _ve($url)), self::READ_ERROR);
    }
}


code:
<?php
/**
 * StatusNet, the distributed open-source microblogging tool
 *
 * Class for an exception when a database lookup returns no results
 *
 * 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   GNUsocial
 * @author    Mikael Nordfeldth <mmn@hethane.se>
 * @copyright 2013 Free Software Foundation, Inc.
 * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html AGPLv3
 * @link      http://www.gnu.org/software/social/
 */

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

class NoObjectTypeException extends ServerException
{
    public $stored;    // The object with query that gave no results

    public function __construct(Notice $stored)
    {
        $this->stored = $stored;
        parent::__construct(sprintf(_('Notice has no object type.')));
    }
}


code:
<?php
/**
 * StatusNet, the distributed open-source microblogging tool
 *
 * Class for an exception when a database lookup returns no results
 *
 * 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   GNUsocial
 * @author    Mikael Nordfeldth <mmn@hethane.se>
 * @copyright 2013 Free Software Foundation, Inc.
 * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html AGPLv3
 * @link      http://www.gnu.org/software/social/
 */

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

class NoParentNoticeException extends ServerException
{
    public $notice;    // The notice which has no parent

    public function __construct(Notice $notice)
    {
        $this->notice = $notice;
        parent::__construct(sprintf(_('No parent for notice with ID "%s".'), $this->notice->id));
    }
}


code:
<?php
/**
 * StatusNet, the distributed open-source microblogging tool
 *
 * Parent class for an exception when a profile is missing
 *
 * 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 2010 StatusNet, Inc.
 * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html AGPLv3
 * @link      http://status.net/
 */

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

/**
 * Parent class for an exception when a profile is missing
 *
 * @category Exception
 * @package  StatusNet
 * @author   Evan Prodromou <evan@status.net>
 * @license  http://www.fsf.org/licensing/licenses/agpl-3.0.html AGPLv3
 * @link     http://status.net/
 */

class NoProfileException extends ServerException
{
    public $profile_id = null;

    public function __construct($profile_id, $msg=null)
    {
        $this->profile_id = $profile_id;

        if ($msg === null) {
            // TRANS: Exception text shown when no profile can be found for a user.
            // TRANS: %u is a profile ID (number).
            $msg = sprintf(_('There is no profile with id==%u'), $this->profile_id);
        }

        parent::__construct($msg, 404);
    }
}


code:
<?php
/**
 * StatusNet, the distributed open-source microblogging tool
 *
 * Class for an exception when there is no queuehandler for this transport type
 *
 * 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   GNUsocial
 * @author    Mikael Nordfeldth <mmn@hethane.se>
 * @copyright 2016 Free Software Foundation, Inc.
 * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html AGPLv3
 * @link      http://www.gnu.org/software/social/
 */

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

class NoQueueHandlerException extends ServerException
{
    public $transport;    // The object with query that gave no results

    public function __construct($transport)
    {
        $this->transport = $transport;
        parent::__construct(sprintf(_('No queue handler found for transport %s.'), _ve($this->transport)));
    }
}