code:
<?php
/**
 * GNU social - a federating social network
 *
 * Abstraction for files
 *
 * 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  Files
 * @package   GNUsocial
 * @author    Mikael Nordfeldth <mmn@hethane.se>
 * @author    Miguel Dantas <biodantas@gmail.com>
 * @copyright 2008-2009, 2019 Free Software Foundation http://fsf.org
 * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
 * @link      https://www.gnu.org/software/social/
 */

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

/**
 * Table Definition for file
 */
class File extends Managed_DataObject
{
    public $__table = 'file';                            // table name
    public $id;                              // int(4)  primary_key not_null
    public $urlhash;                         // varchar(64)  unique_key
    public $url;                             // text
    public $filehash;                        // varchar(64)     indexed
    public $mimetype;                        // varchar(50)
    public $size;                            // int(4)
    public $title;                           // text()
    public $date;                            // int(4)
    public $protected;                       // int(4)
    public $filename;                        // text()
    public $width;                           // int(4)
    public $height;                          // int(4)
    public $modified;                        // timestamp()   not_null default_CURRENT_TIMESTAMP

    const URLHASH_ALG = 'sha256';
    const FILEHASH_ALG = 'sha256';

    public static function schemaDef()
    {
        return array(
            'fields' => array(
                'id' => array('type' => 'serial', 'not null' => true),
                'urlhash' => array('type' => 'varchar', 'length' => 64, 'not null' => true, 'description' => 'sha256 of destination URL (url field)'),
                'url' => array('type' => 'text', 'description' => 'destination URL after following possible redirections'),
                'filehash' => array('type' => 'varchar', 'length' => 64, 'not null' => false, 'description' => 'sha256 of the file contents, only for locally stored files of course'),
                'mimetype' => array('type' => 'varchar', 'length' => 50, 'description' => 'mime type of resource'),
                'size' => array('type' => 'int', 'description' => 'size of resource when available'),
                'title' => array('type' => 'text', 'description' => 'title of resource when available'),
                'date' => array('type' => 'int', 'description' => 'date of resource according to http query'),
                'protected' => array('type' => 'int', 'description' => 'true when URL is private (needs login)'),
                'filename' => array('type' => 'text', 'description' => 'if file is stored locally (too) this is the filename'),
                'width' => array('type' => 'int', 'description' => 'width in pixels, if it can be described as such and data is available'),
                'height' => array('type' => 'int', 'description' => 'height in pixels, if it can be described as such and data is available'),

                'modified' => array('type' => 'timestamp', 'not null' => true, 'description' => 'date this record was modified'),
            ),
            'primary key' => array('id'),
            'unique keys' => array(
                'file_urlhash_key' => array('urlhash'),
            ),
            'indexes' => array(
                'file_filehash_idx' => array('filehash'),
            ),
        );
    }

    public static function isProtected($url)
    {
        $protected_urls_exps = array(
            'https://www.facebook.com/login.php',
            common_path('main/login')
            );

        foreach ($protected_urls_exps as $protected_url_exp) {
            if (preg_match('!^'.preg_quote($protected_url_exp).'(.*)$!i', $url) === 1) {
                return true;
            }
        }

        return false;
    }

    /**
     * Save a new file record.
     *
     * @param array $redir_data lookup data eg from File_redirection::where()
     * @param string $given_url
     * @return File
     * @throws ServerException
     */
    public static function saveNew(array $redir_data, $given_url)
    {
        $file = null;
        try {
            // I don't know why we have to keep doing this but we run a last check to avoid
            // uniqueness bugs.
            $file = File::getByUrl($given_url);
            return $file;
        } catch (NoResultException $e) {
            // We don't have the file's URL since before, so let's continue.
        }

        // if the given url is an local attachment url and the id already exists, don't
        // save a new file record. This should never happen, but let's make it foolproof
        // FIXME: how about attachments servers?
        $u = parse_url($given_url);
        if (isset($u['host']) && $u['host'] === common_config('site', 'server')) {
            $r = Router::get();
            // Skip the / in the beginning or $r->map won't match
            try {
                $args = $r->map(mb_substr($u['path'], 1));
                if ($args['action'] === 'attachment') {
                    try {
                        // $args['attachment'] should always be set if action===attachment, given our routing rules
                        $file = File::getByID($args['attachment']);
                        return $file;
                    } catch (EmptyPkeyValueException $e) {
                        // ...but $args['attachment'] can also be 0...
                    } catch (NoResultException $e) {
                        // apparently this link goes to us, but is _not_ an existing attachment (File) ID?
                    }
                }
            } catch (Exception $e) {
                // Some other exception was thrown from $r->map, likely a
                // ClientException (404) because of some malformed link to
                // our own instance. It's still a valid URL however, so we
                // won't abort anything... I noticed this when linking:
                // https://social.umeahackerspace.se/mmn/foaf' (notice the
                // apostrophe in the end, making it unrecognizable for our
                // URL routing.
                // That specific issue (the apostrophe being part of a link
                // is something that may or may not have been fixed since,
                // in lib/util.php in common_replace_urls_callback().
            }
        }

        $file = new File;
        $file->url = $given_url;
        if (!empty($redir_data['protected'])) {
            $file->protected = $redir_data['protected'];
        }
        if (!empty($redir_data['title'])) {
            $file->title = $redir_data['title'];
        }
        if (!empty($redir_data['type'])) {
            $file->mimetype = $redir_data['type'];
        }
        if (!empty($redir_data['size'])) {
            $file->size = intval($redir_data['size']);
        }
        if (isset($redir_data['time']) && $redir_data['time'] > 0) {
            $file->date = intval($redir_data['time']);
        }
        $file->saveFile();
        return $file;
    }

    public function saveFile()
    {
        $this->urlhash = self::hashurl($this->url);

        if (!Event::handle('StartFileSaveNew', array(&$this))) {
            throw new ServerException('File not saved due to an aborted StartFileSaveNew event.');
        }

        $this->id = $this->insert();

        if ($this->id === false) {
            throw new ServerException('File/URL metadata could not be saved to the database.');
        }

        Event::handle('EndFileSaveNew', array($this));
    }

    /**
     * Go look at a URL and possibly save data about it if it's new:
     * - follow redirect chains and store them in file_redirection
     * - if a thumbnail is available, save it in file_thumbnail
     * - save file record with basic info
     * - optionally save a file_to_post record
     * - return the File object with the full reference
     *
     * @param string $given_url the URL we're looking at
     * @param Notice $notice (optional)
     * @param bool $followRedirects defaults to true
     *
     * @return mixed File on success, -1 on some errors
     *
     * @throws ServerException on failure
     */
    public static function processNew($given_url, Notice $notice=null, $followRedirects=true)
    {
        if (empty($given_url)) {
            throw new ServerException('No given URL to process');
        }

        $given_url = File_redirection::_canonUrl($given_url);
        if (empty($given_url)) {
            throw new ServerException('No canonical URL from given URL to process');
        }

        $redir = File_redirection::where($given_url);
        try {
            $file = $redir->getFile();
        } catch (EmptyPkeyValueException $e) {
            common_log(LOG_ERR, 'File_redirection::where gave object with empty file_id for given_url '._ve($given_url));
            throw new ServerException('URL processing failed without new File object');
        } catch (NoResultException $e) {
            // This should not happen
            common_log(LOG_ERR, 'File_redirection after discovery could still not return a File object.');
            throw new ServerException('URL processing failed without new File object');
        }

        if ($notice instanceof Notice) {
            File_to_post::processNew($file, $notice);
        }

        return $file;
    }

    public static function respectsQuota(Profile $scoped, $fileSize)
    {
        if ($fileSize > common_config('attachments', 'file_quota')) {
            // TRANS: Message used to be inserted as %2$s in  the text "No file may
            // TRANS: be larger than %1$d byte and the file you sent was %2$s.".
            // TRANS: %1$d is the number of bytes of an uploaded file.
            $fileSizeText = sprintf(_m('%1$d byte', '%1$d bytes', $fileSize), $fileSize);

            $fileQuota = common_config('attachments', 'file_quota');
            // TRANS: Message given if an upload is larger than the configured maximum.
            // TRANS: %1$d (used for plural) is the byte limit for uploads,
            // TRANS: %2$s is the proper form of "n bytes". This is the only ways to have
            // TRANS: gettext support multiple plurals in the same message, unfortunately...
            throw new ClientException(
                sprintf(
                        _m(
                        'No file may be larger than %1$d byte and the file you sent was %2$s. Try to upload a smaller version.',
                        'No file may be larger than %1$d bytes and the file you sent was %2$s. Try to upload a smaller version.',
                        $fileQuota
                    ),
                        $fileQuota,
                        $fileSizeText
                    )
            );
        }

        $file = new File;

        $query = "select sum(size) as total from file join file_to_post on file_to_post.file_id = file.id join notice on file_to_post.post_id = notice.id where profile_id = {$scoped->id} and file.url like '%/notice/%/file'";
        $file->query($query);
        $file->fetch();
        $total = $file->total + $fileSize;
        if ($total > common_config('attachments', 'user_quota')) {
            // TRANS: Message given if an upload would exceed user quota.
            // TRANS: %d (number) is the user quota in bytes and is used for plural.
            throw new ClientException(
                sprintf(
                        _m(
                        'A file this large would exceed your user quota of %d byte.',
                        'A file this large would exceed your user quota of %d bytes.',
                        common_config('attachments', 'user_quota')
                    ),
                        common_config('attachments', 'user_quota')
                    )
            );
        }
        $query .= ' AND EXTRACT(month FROM file.modified) = EXTRACT(month FROM now()) and EXTRACT(year FROM file.modified) = EXTRACT(year FROM now())';
        $file->query($query);
        $file->fetch();
        $total = $file->total + $fileSize;
        if ($total > common_config('attachments', 'monthly_quota')) {
            // TRANS: Message given id an upload would exceed a user's monthly quota.
            // TRANS: $d (number) is the monthly user quota in bytes and is used for plural.
            throw new ClientException(
                sprintf(
                        _m(
                        'A file this large would exceed your monthly quota of %d byte.',
                        'A file this large would exceed your monthly quota of %d bytes.',
                        common_config('attachments', 'monthly_quota')
                    ),
                        common_config('attachments', 'monthly_quota')
                    )
            );
        }
        return true;
    }

    public function getFilename()
    {
        return self::tryFilename($this->filename);
    }

    public function getSize()
    {
        return intval($this->size);
    }

    // where should the file go?

    public static function filename(Profile $profile, $origname, $mimetype)
    {
        $ext = self::guessMimeExtension($mimetype, $origname);

        // Normalize and make the original filename more URL friendly.
        $origname = basename($origname, ".$ext");
        if (class_exists('Normalizer')) {
            // http://php.net/manual/en/class.normalizer.php
            // http://www.unicode.org/reports/tr15/
            $origname = Normalizer::normalize($origname, Normalizer::FORM_KC);
        }
        $origname = preg_replace('/[^A-Za-z0-9\.\_]/', '_', $origname);

        $nickname = $profile->getNickname();
        $datestamp = strftime('%Y%m%d', time());
        do {
            // generate new random strings until we don't run into a filename collision.
            $random = strtolower(common_confirmation_code(16));
            $filename = "$nickname-$datestamp-$origname-$random.$ext";
        } while (file_exists(self::path($filename)));
        return $filename;
    }

    /**
     * @param string $filename
     * @return string|bool Value from the 'extblacklist' array, in the config
     */
    public static function getSafeExtension(string $filename) {
        if (preg_match('/^.+?\.([A-Za-z0-9]+)$/', $filename, $matches)) {
            // we matched on a file extension, so let's see if it means something.
            $ext = mb_strtolower($matches[1]);
            $blacklist = common_config('attachments', 'extblacklist');
            // If we got an extension from $filename we want to check if it's in a blacklist
            // so we avoid people uploading restricted files
            if (array_key_exists($ext, $blacklist)) {
                if (!is_string($blacklist[$ext])) {
                    return false;
                }
                // return a safe replacement extension ('php' => 'phps' for example)
                return $blacklist[$ext];
            }
            // the attachment extension based on its filename was not blacklisted so it's ok to use it
            return $ext;
        } else {
            return false;
        }
    }

    /**
     * @param $mimetype string The mimetype we've discovered for this file.
     * @param $filename string An optional filename which we can use on failure.
     * @return mixed|string
     * @throws ClientException
     */
    public static function guessMimeExtension($mimetype, $filename=null)
    {
        try {
            // first see if we know the extension for our mimetype
            $ext = common_supported_mime_to_ext($mimetype);
            // we do, so use it!
            return $ext;
        } catch (UnknownMimeExtensionException $e) {
            // We don't know the extension for this mimetype, but let's guess.
            // If we can't recognize the extension from the MIME, we try
            // to guess based on filename, if one was supplied.
            if (!is_null($filename)) {
                $ext = getSafeExtension($filename);
                if ($ext === false) {
                    // we don't have a safe replacement extension
                    throw new ClientException(_('Blacklisted file extension.'));
                } else {
                    return $ext;
                }
            }
        } catch (Exception $e) {
            common_log(LOG_INFO, 'Problem when figuring out extension for mimetype: '._ve($e));
        }

        // If nothing else has given us a result, try to extract it from
        // the mimetype value (this turns .jpg to .jpeg for example...)
        $matches = array();
        // Will get jpeg from image/jpeg as well as json from application/jrd+json
        if (!preg_match('/[\/+-\.]([a-z0-9]+)/', mb_strtolower($mimetype), $matches)) {
            throw new Exception("Malformed mimetype: {$mimetype}");
        }
        return mb_strtolower($matches[1]);
    }

    /**
     * Validation for as-saved base filenames
     * @param $filename
     * @return false|int
     */
    public static function validFilename($filename)
    {
        return preg_match('/^[A-Za-z0-9._-]+$/', $filename);
    }

    public static function tryFilename($filename)
    {
        if (!self::validFilename($filename)) {
            throw new InvalidFilenameException($filename);
        }
        // if successful, return the filename for easy if-statementing
        return $filename;
    }

    /**
     * @param $filename
     * @return string
     * @throws InvalidFilenameException
     */
    public static function path($filename)
    {
        self::tryFilename($filename);

        $dir = common_config('attachments', 'dir');

        if (!in_array($dir[mb_strlen($dir)-1], ['/', '\\'])) {
            $dir .= DIRECTORY_SEPARATOR;
        }

        return $dir . $filename;
    }

    public static function url($filename)
    {
        self::tryFilename($filename);

        if (common_config('site', 'private')) {
            return common_local_url(
                'getfile',
                array('filename' => $filename)
            );
        }

        if (GNUsocial::useHTTPS()) {
            $sslserver = common_config('attachments', 'sslserver');

            if (empty($sslserver)) {
                // XXX: this assumes that background dir == site dir + /file/
                // not true if there's another server
                if (is_string(common_config('site', 'sslserver')) &&
                    mb_strlen(common_config('site', 'sslserver')) > 0) {
                    $server = common_config('site', 'sslserver');
                } elseif (common_config('site', 'server')) {
                    $server = common_config('site', 'server');
                }
                $path = common_config('site', 'path') . '/file/';
            } else {
                $server = $sslserver;
                $path   = common_config('attachments', 'sslpath');
                if (empty($path)) {
                    $path = common_config('attachments', 'path');
                }
            }

            $protocol = 'https';
        } else {
            $path = common_config('attachments', 'path');
            $server = common_config('attachments', 'server');

            if (empty($server)) {
                $server = common_config('site', 'server');
            }

            $ssl = common_config('attachments', 'ssl');

            $protocol = ($ssl) ? 'https' : 'http';
        }

        if ($path[strlen($path)-1] != '/') {
            $path .= '/';
        }

        if ($path[0] != '/') {
            $path = '/'.$path;
        }

        return $protocol.'://'.$server.$path.$filename;
    }

    public static $_enclosures = array();

    public function getEnclosure()
    {
        if (isset(self::$_enclosures[$this->getID()])) {
            return self::$_enclosures[$this->getID()];
        }

        $enclosure = (object) array();
        foreach (array('title', 'url', 'date', 'modified', 'size', 'mimetype', 'width', 'height') as $key) {
            if ($this->$key !== '') {
                $enclosure->$key = $this->$key;
            }
        }

        $needMoreMetadataMimetypes = array(null, 'application/xhtml+xml', 'text/html');

        if (!isset($this->filename) && in_array(common_bare_mime($enclosure->mimetype), $needMoreMetadataMimetypes)) {
            // This fetches enclosure metadata for non-local links with unset/HTML mimetypes,
            // which may be enriched through oEmbed or similar (implemented as plugins)
            Event::handle('FileEnclosureMetadata', array($this, &$enclosure));
        }
        if (empty($enclosure->mimetype)) {
            // This means we either don't know what it is, so it can't
            // be shown as an enclosure, or it is an HTML link which
            // does not link to a resource with further metadata.
            throw new ServerException('Unknown enclosure mimetype, not enough metadata');
        }

        self::$_enclosures[$this->getID()] = $enclosure;
        return $enclosure;
    }

    public function hasThumbnail()
    {
        try {
            $this->getThumbnail();
        } catch (Exception $e) {
            return false;
        }
        return true;
    }

    /**
     * Get the attachment's thumbnail record, if any.
     * Make sure you supply proper 'int' typed variables (or null).
     *
     * @param $width  int   Max width of thumbnail in pixels. (if null, use common_config values)
     * @param $height int   Max height of thumbnail in pixels. (if null, square-crop to $width)
     * @param $crop   bool  Crop to the max-values' aspect ratio
     * @param $force_still  bool    Don't allow fallback to showing original (such as animated GIF)
     * @param $upscale      mixed   Whether or not to scale smaller images up to larger thumbnail sizes. (null = site default)
     *
     * @return File_thumbnail
     *
     * @throws UseFileAsThumbnailException  if the file is considered an image itself and should be itself as thumbnail
     * @throws UnsupportedMediaException    if, despite trying, we can't understand how to make a thumbnail for this format
     * @throws ServerException              on various other errors
     */
    public function getThumbnail($width=null, $height=null, $crop=false, $force_still=true, $upscale=null)
    {
        // Get some more information about this file through our ImageFile class
        $image = ImageFile::fromFileObject($this);
        if ($image->animated && !common_config('thumbnail', 'animated')) {
            // null  means "always use file as thumbnail"
            // false means you get choice between frozen frame or original when calling getThumbnail
            if (is_null(common_config('thumbnail', 'animated')) || !$force_still) {
                try {
                    // remote files with animated GIFs as thumbnails will match this
                    return File_thumbnail::byFile($this);
                } catch (NoResultException $e) {
                    // and if it's not a remote file, it'll be safe to use the locally stored File
                    throw new UseFileAsThumbnailException($this);
                }
            }
        }

        return $image->getFileThumbnail(
            $width,
            $height,
            $crop,
            !is_null($upscale) ? $upscale : common_config('thumbnail', 'upscale')
        );
    }

    public function getPath()
    {
        $filepath = self::path($this->filename);
        if (!file_exists($filepath)) {
            throw new FileNotFoundException($filepath);
        }
        return $filepath;
    }

    public function getAttachmentUrl()
    {
        return common_local_url('attachment', array('attachment'=>$this->getID()));
    }

    public function getAttachmentDownloadUrl()
    {
        return common_local_url('attachment_download', array('attachment'=>$this->getID()));
    }

    public function getAttachmentViewUrl()
    {
        return common_local_url('attachment_view', array('attachment'=>$this->getID()));
    }

    /**
     * @param mixed $use_local true means require local, null means prefer local, false means use whatever is stored
     * @return string
     * @throws FileNotStoredLocallyException
     */
    public function getUrl($use_local=null)
    {
        if ($use_local !== false) {
            if (is_string($this->filename) || !empty($this->filename)) {
                // A locally stored file, so let's generate a URL for our instance.
                return $this->getAttachmentViewUrl();
            }
            if ($use_local) {
                // if the file wasn't stored locally (has filename) and we require a local URL
                throw new FileNotStoredLocallyException($this);
            }
        }

        // No local filename available, return the URL we have stored
        return $this->url;
    }

    public static function getByUrl($url)
    {
        $file = new File();
        $file->urlhash = self::hashurl($url);
        if (!$file->find(true)) {
            throw new NoResultException($file);
        }
        return $file;
    }

    /**
     * @param string $hashstr String of (preferrably lower case) hexadecimal characters, same as result of 'hash_file(...)'
     * @return File
     * @throws NoResultException
     */
    public static function getByHash($hashstr)
    {
        $file = new File();
        $file->filehash = strtolower($hashstr);
        if (!$file->find(true)) {
            throw new NoResultException($file);
        }
        return $file;
    }

    public function updateUrl($url)
    {
        $file = File::getKV('urlhash', self::hashurl($url));
        if ($file instanceof File) {
            throw new ServerException('URL already exists in DB');
        }
        $sql = 'UPDATE %1$s SET urlhash=%2$s, url=%3$s WHERE urlhash=%4$s;';
        $result = $this->query(sprintf(
            $sql,
            $this->tableName(),
            $this->_quote((string)self::hashurl($url)),
            $this->_quote((string)$url),
            $this->_quote((string)$this->urlhash)
        ));
        if ($result === false) {
            common_log_db_error($this, 'UPDATE', __FILE__);
            throw new ServerException("Could not UPDATE {$this->tableName()}.url");
        }

        return $result;
    }

    /**
     * Blow the cache of notices that link to this URL
     *
     * @param boolean $last Whether to blow the "last" cache too
     *
     * @return void
     */

    public function blowCache($last=false)
    {
        self::blow('file:notice-ids:%s', $this->id);
        if ($last) {
            self::blow('file:notice-ids:%s;last', $this->id);
        }
        self::blow('file:notice-count:%d', $this->id);
    }

    /**
     * Stream of notices linking to this URL
     *
     * @param integer $offset   Offset to show; default is 0
     * @param integer $limit    Limit of notices to show
     * @param integer $since_id Since this notice
     * @param integer $max_id   Before this notice
     *
     * @return array ids of notices that link to this file
     */

    public function stream($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $max_id=0)
    {
        // FIXME: Try to get the Profile::current() here in some other way to avoid mixing
        // the current session user with possibly background/queue processing.
        $stream = new FileNoticeStream($this, Profile::current());
        return $stream->getNotices($offset, $limit, $since_id, $max_id);
    }

    public function noticeCount()
    {
        $cacheKey = sprintf('file:notice-count:%d', $this->id);

        $count = self::cacheGet($cacheKey);

        if ($count === false) {
            $f2p = new File_to_post();

            $f2p->file_id = $this->id;

            $count = $f2p->count();

            self::cacheSet($cacheKey, $count);
        }

        return $count;
    }

    public function isLocal()
    {
        return !empty($this->filename);
    }

    public function delete($useWhere=false)
    {
        // Delete the file, if it exists locally
        if (!empty($this->filename) && file_exists(self::path($this->filename))) {
            $deleted = @unlink(self::path($this->filename));
            if (!$deleted) {
                common_log(LOG_ERR, sprintf('Could not unlink existing file: "%s"', self::path($this->filename)));
            }
        }

        // Clear out related things in the database and filesystem, such as thumbnails
        if (Event::handle('FileDeleteRelated', array($this))) {
            $thumbs = new File_thumbnail();
            $thumbs->file_id = $this->id;
            if ($thumbs->find()) {
                while ($thumbs->fetch()) {
                    $thumbs->delete();
                }
            }

            $f2p = new File_to_post();
            $f2p->file_id = $this->id;
            if ($f2p->find()) {
                while ($f2p->fetch()) {
                    $f2p->delete();
                }
            }
        }

        // And finally remove the entry from the database
        return parent::delete($useWhere);
    }

    public function getTitle()
    {
        $title = $this->title ?: MediaFile::getDisplayName($this);

        return $title ?: null;
    }

    public function setTitle($title)
    {
        $orig = clone($this);
        $this->title = mb_strlen($title) > 0 ? $title : null;
        return $this->update($orig);
    }

    public static function hashurl($url)
    {
        if (empty($url)) {
            throw new Exception('No URL provided to hash algorithm.');
        }
        return hash(self::URLHASH_ALG, $url);
    }

    public static function beforeSchemaUpdate()
    {
        $table = strtolower(get_called_class());
        $schema = Schema::get();
        $schemadef = $schema->getTableDef($table);

        // 2015-02-19 We have to upgrade our table definitions to have the urlhash field populated
        if (isset($schemadef['fields']['urlhash']) && isset($schemadef['unique keys']['file_urlhash_key'])) {
            // We already have the urlhash field, so no need to migrate it.
            return;
        }
        echo "\nFound old $table table, upgrading it to contain 'urlhash' field...";

        $file = new File();
        $file->query(sprintf('SELECT id, LEFT(url, 191) AS shortenedurl, COUNT(*) AS c FROM %1$s WHERE LENGTH(url)>191 GROUP BY shortenedurl HAVING c > 1', $schema->quoteIdentifier($table)));
        print "\nFound {$file->N} URLs with too long entries in file table\n";
        while ($file->fetch()) {
            // We've got a URL that is too long for our future file table
            // so we'll cut it. We could save the original URL, but there is
            // no guarantee it is complete anyway since the previous max was 255 chars.
            $dupfile = new File();
            // First we find file entries that would be duplicates of this when shortened
            // ... and we'll just throw the dupes out the window for now! It's already so borken.
            $dupfile->query(sprintf('SELECT * FROM file WHERE LEFT(url, 191) = %1$s', $dupfile->_quote($file->shortenedurl)));
            // Leave one of the URLs in the database by using ->find(true) (fetches first entry)
            if ($dupfile->find(true)) {
                print "\nShortening url entry for $table id: {$file->id} [";
                $orig = clone($dupfile);
                $origurl = $dupfile->url;   // save for logging purposes
                $dupfile->url = $file->shortenedurl;    // make sure it's only 191 chars from now on
                $dupfile->update($orig);
                print "\nDeleting duplicate entries of too long URL on $table id: {$file->id} [";
                // only start deleting with this fetch.
                while ($dupfile->fetch()) {
                    common_log(LOG_INFO, sprintf('Deleting duplicate File entry of %1$d: %2$d (original URL: %3$s collides with these first 191 characters: %4$s', $dupfile->id, $file->id, $origurl, $file->shortenedurl));
                    print ".";
                    $dupfile->delete();
                }
                print "]\n";
            } else {
                print "\nWarning! URL suddenly disappeared from database: {$file->url}\n";
            }
        }
        echo "...and now all the non-duplicates which are longer than 191 characters...\n";
        $file->query('UPDATE file SET url=LEFT(url, 191) WHERE LENGTH(url)>191');

        echo "\n...now running hacky pre-schemaupdate change for $table:";
        // We have to create a urlhash that is _not_ the primary key,
        // transfer data and THEN run checkSchema
        $schemadef['fields']['urlhash'] = array(
                                              'type' => 'varchar',
                                              'length' => 64,
                                              'not null' => false,  // this is because when adding column, all entries will _be_ NULL!
                                              'description' => 'sha256 of destination URL (url field)',
                                            );
        $schemadef['fields']['url'] = array(
                                              'type' => 'text',
                                              'description' => 'destination URL after following possible redirections',
                                            );
        unset($schemadef['unique keys']);
        $schema->ensureTable($table, $schemadef);
        echo "DONE.\n";

        $classname = ucfirst($table);
        $tablefix = new $classname;
        // urlhash is hash('sha256', $url) in the File table
        echo "Updating urlhash fields in $table table...";
        // Maybe very MySQL specific :(
        $tablefix->query(sprintf(
            'UPDATE %1$s SET %2$s=%3$s;',
            $schema->quoteIdentifier($table),
            'urlhash',
                            // The line below is "result of sha256 on column `url`"
                            'SHA2(url, 256)'
        ));
        echo "DONE.\n";
        echo "Resuming core schema upgrade...";
    }
}


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

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

/**
 * Table Definition for file_redirection
 */

class File_redirection extends Managed_DataObject
{
    ###START_AUTOCODE
    /* the code below is auto generated do not remove the above tag */

    public $__table = 'file_redirection';                // table name
    public $urlhash;                         // varchar(64) primary_key not_null
    public $url;                             // text
    public $file_id;                         // int(4)
    public $redirections;                    // int(4)
    public $httpcode;                        // int(4)
    public $modified;                        // timestamp()   not_null default_CURRENT_TIMESTAMP

    /* the code above is auto generated do not remove the tag below */
    ###END_AUTOCODE

    protected $file; /* Cache the associated file sometimes */

    public static function schemaDef()
    {
        return array(
            'fields' => array(
                'urlhash' => array('type' => 'varchar', 'length' => 64, 'not null' => true, 'description' => 'sha256 hash of the URL'),
                'url' => array('type' => 'text', 'description' => 'short URL (or any other kind of redirect) for file (id)'),
                'file_id' => array('type' => 'int', 'description' => 'short URL for what URL/file'),
                'redirections' => array('type' => 'int', 'description' => 'redirect count'),
                'httpcode' => array('type' => 'int', 'description' => 'HTTP status code (20x, 30x, etc.)'),
                'modified' => array('type' => 'timestamp', 'not null' => true, 'description' => 'date this record was modified'),
            ),
            'primary key' => array('urlhash'),
            'foreign keys' => array(
                'file_redirection_file_id_fkey' => array('file' => array('file_id' => 'id')),
            ),
        );
    }

    static public function getByUrl($url)
    {
        return self::getByPK(array('urlhash' => File::hashurl($url)));
    }

    static function _commonHttp($url, $redirs) {
        $request = new HTTPClient($url);
        $request->setConfig(array(
            'connect_timeout' => 10, // # seconds to wait
            'max_redirs' => $redirs, // # max number of http redirections to follow
            'follow_redirects' => false, // We follow redirects ourselves in lib/httpclient.php
            'store_body' => false, // We won't need body content here.
        ));
        return $request;
    }

    /**
     * Check if this URL is a redirect and return redir info.
     *
     * Most code should call File_redirection::where instead, to check if we
     * already know that redirection and avoid extra hits to the web.
     *
     * The URL is hit and any redirects are followed, up to 10 levels or until
     * a protected URL is reached.
     *
     * @param string $in_url
     * @return mixed one of:
     *         string - target URL, if this is a direct link or can't be followed
     *         array - redirect info if this is an *unknown* redirect:
     *              associative array with the following elements:
     *                code: HTTP status code
     *                redirects: count of redirects followed
     *                url: URL string of final target
     *                type (optional): MIME type from Content-Type header
     *                size (optional): byte size from Content-Length header
     *                time (optional): timestamp from Last-Modified header
     */
    static function lookupWhere($short_url, $redirs = 10, $protected = false) {
        if ($redirs < 0) return false;

        if(strpos($short_url,'://') === false){
            return $short_url;
        }
        try {
            $request = self::_commonHttp($short_url, $redirs);
            // Don't include body in output
            $request->setMethod(HTTP_Request2::METHOD_HEAD);
            $response = $request->send();

            if (405 == $response->getStatus() || 204 == $response->getStatus()) {
                // HTTP 405 Unsupported Method
                // Server doesn't support HEAD method? Can this really happen?
                // We'll try again as a GET and ignore the response data.
                //
                // HTTP 204 No Content
                // YFrog sends 204 responses back for our HEAD checks, which
                // seems like it may be a logic error in their servers. If
                // we get a 204 back, re-run it as a GET... if there's really
                // no content it'll be cheap. :)
                $request = self::_commonHttp($short_url, $redirs);
                $response = $request->send();
            } elseif (400 == $response->getStatus()) {
                throw new Exception('Got error 400 on HEAD request, will not go further.');
            }
        } catch (Exception $e) {
            // Invalid URL or failure to reach server
            common_log(LOG_ERR, "Error while following redirects for $short_url: " . $e->getMessage());
            return $short_url;
        }

		// if last url after all redirections is protected,
		// use the url before it in the redirection chain
        if ($response->getRedirectCount() && File::isProtected($response->getEffectiveUrl())) {
			$return_url = $response->redirUrls[$response->getRedirectCount()-1];
        } else {
			$return_url = $response->getEffectiveUrl();
        }

        $ret = array('code' => $response->getStatus()
                , 'redirects' => $response->getRedirectCount()
                , 'url' => $return_url);

        $type = $response->getHeader('Content-Type');
        if ($type) $ret['type'] = $type;
        if ($protected) $ret['protected'] = true;
        $size = $response->getHeader('Content-Length'); // @fixme bytes?
        if ($size) $ret['size'] = $size;
        $time = $response->getHeader('Last-Modified');
        if ($time) $ret['time'] = strtotime($time);
        return $ret;
    }

    /**
     * Check if this URL is a redirect and return redir info.
     * If a File record is present for this URL, it is not considered a redirect.
     * If a File_redirection record is present for this URL, the recorded target is returned.
     *
     * If no File or File_redirect record is present, the URL is hit and any
     * redirects are followed, up to 10 levels or until a protected URL is
     * reached.
     *
     * @param string $in_url
     * @param boolean $discover true to attempt dereferencing the redirect if we don't know it already
     * @return File_redirection
     */
    static function where($in_url, $discover=true) {
        $redir = new File_redirection();
        $redir->url = $in_url;
        $redir->urlhash = File::hashurl($redir->url);
        $redir->redirections = 0;

        try {
            $r = File_redirection::getByUrl($in_url);

            try {
                $f = File::getByID($r->file_id);
                $r->file = $f;
                $r->redir_url = $f->url;
            } catch (NoResultException $e) {
                // Invalid entry, delete and run again
                common_log(LOG_ERR, "Could not find File with id=".$r->file_id." referenced in File_redirection, deleting File redirection entry and and trying again...");
                $r->delete();
                return self::where($in_url);
            }

            // File_redirecion and File record found, return both
            return $r;

        } catch (NoResultException $e) {
            // File_redirecion record not found, but this might be a direct link to a file
            try {
                $f = File::getByUrl($in_url);
                $redir->file_id = $f->id;
                $redir->file = $f;
                return $redir;
            } catch (NoResultException $e) {
                // nope, this was not a direct link to a file either, let's keep going
            }
        }

        if ($discover) {
            // try to follow redirects and get the final url
            $redir_info = File_redirection::lookupWhere($in_url);
            if(is_string($redir_info)) {
                $redir_info = array('url' => $redir_info);
            }

            // the last url in the redirection chain can actually be a redirect!
            // this is the case with local /attachment/{file_id} links
            // in that case we have the file id already
            try {
                $r = File_redirection::getByUrl($redir_info['url']);

                $f = File::getKV('id',$r->file_id);

                if($f instanceof File) {
                    $redir->file = $f;
                    $redir->redir_url = $f->url;
                } else {
                    // Invalid entry in File_redirection, delete and run again
                    common_log(LOG_ERR, "Could not find File with id=".$r->file_id." referenced in File_redirection, deleting File_redirection entry and trying again...");
                    $r->delete();
                    return self::where($in_url);
                }
            } catch (NoResultException $e) {
                // save the file now when we know that we don't have it in File_redirection
                try {
                    $redir->file = File::saveNew($redir_info,$redir_info['url']);
                } catch (ServerException $e) {
                    common_log(LOG_ERR, $e);
                }
            }

            // If this is a redirection and we have a file to redirect to, save it
            // (if it doesn't exist in File_redirection already)
            if($redir->file instanceof File && $redir_info['url'] != $in_url) {
                try {
                    $file_redir = File_redirection::getByUrl($in_url);
                } catch (NoResultException $e) {
                    $file_redir = new File_redirection();
                    $file_redir->urlhash = File::hashurl($in_url);
                    $file_redir->url = $in_url;
                    $file_redir->file_id = $redir->file->getID();
                    $file_redir->insert();
                    $file_redir->redir_url = $redir->file->url;
                }

                $file_redir->file = $redir->file;
                return $file_redir;
            }
        }

        return $redir;
    }

    /**
     * Shorten a URL with the current user's configured shortening
     * options, if applicable.
     *
     * If it cannot be shortened or the "short" URL is longer than the
     * original, the original is returned.
     *
     * If the referenced item has not been seen before, embedding data
     * may be saved.
     *
     * @param string $long_url
     * @param User $user whose shortening options to use; defaults to the current web session user
     * @return string
     */
    static function makeShort($long_url, $user=null)
    {
        $canon = File_redirection::_canonUrl($long_url);

        $short_url = File_redirection::_userMakeShort($canon, $user);

        // Did we get one? Is it shorter?

        return !empty($short_url) ? $short_url : $long_url;
    }

    /**
     * Shorten a URL with the current user's configured shortening
     * options, if applicable.
     *
     * If it cannot be shortened or the "short" URL is longer than the
     * original, the original is returned.
     *
     * If the referenced item has not been seen before, embedding data
     * may be saved.
     *
     * @param string $long_url
     * @return string
     */

    static function forceShort($long_url, $user)
    {
        $canon = File_redirection::_canonUrl($long_url);

        $short_url = File_redirection::_userMakeShort($canon, $user, true);

        // Did we get one? Is it shorter?
        return !empty($short_url) ? $short_url : $long_url;
    }

    static function _userMakeShort($long_url, User $user=null, $force = false) {
        $short_url = common_shorten_url($long_url, $user, $force);
        if (!empty($short_url) && $short_url != $long_url) {
            $short_url = (string)$short_url;
            // store it
            try {
                $file = File::getByUrl($long_url);
            } catch (NoResultException $e) {
                // Check if the target URL is itself a redirect...
                // This should already have happened in processNew in common_shorten_url()
                $redir = File_redirection::where($long_url);
                $file = $redir->file;
            }
            // Now we definitely have a File object in $file
            try {
                $file_redir = File_redirection::getByUrl($short_url);
            } catch (NoResultException $e) {
                $file_redir = new File_redirection();
                $file_redir->urlhash = File::hashurl($short_url);
                $file_redir->url = $short_url;
                $file_redir->file_id = $file->getID();
                $file_redir->insert();
            }
            return $short_url;
        }
        return null;
    }

    /**
     * Basic attempt to canonicalize a URL, cleaning up some standard variants
     * such as funny syntax or a missing path. Used internally when cleaning
     * up URLs for storage and following redirect chains.
     *
     * Note that despite being on File_redirect, this function DOES NOT perform
     * any dereferencing of redirects.
     *
     * @param string $in_url input URL
     * @param string $default_scheme if given a bare link; defaults to 'http://'
     * @return string
     */
    static function _canonUrl($in_url, $default_scheme = 'http://') {
        if (empty($in_url)) return false;
        $out_url = $in_url;
        $p = parse_url($out_url);
        if (empty($p['host']) || empty($p['scheme'])) {
            list($scheme) = explode(':', $in_url, 2);
            switch (strtolower($scheme)) {
            case 'fax':
            case 'tel':
                $out_url = str_replace('.-()', '', $out_url);
                break;

            // non-HTTP schemes, so no redirects
            case 'bitcoin':
            case 'mailto':
            case 'aim':
            case 'jabber':
            case 'xmpp':
                // don't touch anything
                break;

            // URLs without domain name, so no redirects
            case 'magnet':
                // don't touch anything
                break;

            // URLs with coordinates, not browsable domain names
            case 'geo':
                // don't touch anything
                break;

            default:
                $out_url = $default_scheme . ltrim($out_url, '/');
                $p = parse_url($out_url);
                if (empty($p['scheme'])) return false;
                break;
            }
        }

        if (('ftp' == $p['scheme']) || ('ftps' == $p['scheme']) || ('http' == $p['scheme']) || ('https' == $p['scheme'])) {
            if (empty($p['host'])) return false;
            if (empty($p['path'])) {
                $out_url .= '/';
            }
        }

        return $out_url;
    }

    static function saveNew($data, $file_id, $url) {
        $file_redir = new File_redirection;
        $file_redir->urlhash = File::hashurl($url);
        $file_redir->url = $url;
        $file_redir->file_id = $file_id;
        $file_redir->redirections = intval($data['redirects']);
        $file_redir->httpcode = intval($data['code']);
        $file_redir->insert();
    }

    static public function beforeSchemaUpdate()
    {
        $table = strtolower(get_called_class());
        $schema = Schema::get();
        $schemadef = $schema->getTableDef($table);

        // 2015-02-19 We have to upgrade our table definitions to have the urlhash field populated
        if (isset($schemadef['fields']['urlhash']) && in_array('urlhash', $schemadef['primary key'])) {
            // We already have the urlhash field, so no need to migrate it.
            return;
        }
        echo "\nFound old $table table, upgrading it to contain 'urlhash' field...";
        // We have to create a urlhash that is _not_ the primary key,
        // transfer data and THEN run checkSchema
        $schemadef['fields']['urlhash'] = array (
                                              'type' => 'varchar',
                                              'length' => 64,
                                              'not null' => true,
                                              'description' => 'sha256 hash of the URL',
                                            );
        $schemadef['fields']['url'] = array (
                                              'type' => 'text',
                                              'description' => 'short URL (or any other kind of redirect) for file (id)',
                                            );
        unset($schemadef['primary key']);
        $schema->ensureTable($table, $schemadef);
        echo "DONE.\n";

        $classname = ucfirst($table);
        $tablefix = new $classname;
        // urlhash is hash('sha256', $url) in the File table
        echo "Updating urlhash fields in $table table...";
        // Maybe very MySQL specific :(
        $tablefix->query(sprintf('UPDATE %1$s SET %2$s=%3$s;',
                            $schema->quoteIdentifier($table),
                            'urlhash',
                            // The line below is "result of sha256 on column `url`"
                            'SHA2(url, 256)'));
        echo "DONE.\n";
        echo "Resuming core schema upgrade...";
    }

    public function getFile() {
        if (!$this->file instanceof File) {
            $this->file = File::getByID($this->file_id);
        }

        return $this->file;
    }
}

repo_name: andremichelle/gnu

license: mit


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

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

/**
 * Table Definition for file_thumbnail
 */

class File_thumbnail extends Managed_DataObject
{
    public $__table = 'file_thumbnail';                  // table name
    public $file_id;                         // int(4)  primary_key not_null
    public $urlhash;                         // varchar(64) indexed
    public $url;                             // text
    public $filename;                        // text
    public $width;                           // int(4)  primary_key
    public $height;                          // int(4)  primary_key
    public $modified;                        // timestamp()   not_null default_CURRENT_TIMESTAMP

    const URLHASH_ALG = 'sha256';

    public static function schemaDef()
    {
        return array(
            'fields' => array(
                'file_id' => array('type' => 'int', 'not null' => true, 'description' => 'thumbnail for what URL/file'),
                'urlhash' => array('type' => 'varchar', 'length' => 64, 'description' => 'sha256 of url field if non-empty'),
                'url' => array('type' => 'text', 'description' => 'URL of thumbnail'),
                'filename' => array('type' => 'text', 'description' => 'if stored locally, filename is put here'),
                'width' => array('type' => 'int', 'description' => 'width of thumbnail'),
                'height' => array('type' => 'int', 'description' => 'height of thumbnail'),
                'modified' => array('type' => 'timestamp', 'not null' => true, 'description' => 'date this record was modified'),
            ),
            'primary key' => array('file_id', 'width', 'height'),
            'indexes' => array(
                'file_thumbnail_file_id_idx' => array('file_id'),
                'file_thumbnail_urlhash_idx' => array('urlhash'),
            ),
            'foreign keys' => array(
                'file_thumbnail_file_id_fkey' => array('file', array('file_id' => 'id')),
            )
        );
    }

    /**
     * Save oEmbed-provided thumbnail data
     *
     * @param object $data
     * @param int $file_id
     */
    public static function saveNew($data, $file_id) {
        if (!empty($data->thumbnail_url)) {
            // Non-photo types such as video will usually
            // show us a thumbnail, though it's not required.
            self::saveThumbnail($file_id,
                                $data->thumbnail_url,
                                $data->thumbnail_width,
                                $data->thumbnail_height);
        } else if ($data->type == 'photo') {
            // The inline photo URL given should also fit within
            // our requested thumbnail size, per oEmbed spec.
            self::saveThumbnail($file_id,
                                $data->url,
                                $data->width,
                                $data->height);
        }
    }

    /**
     * Fetch an entry by using a File's id
     *
     * @param   File    $file       The File object we're getting a thumbnail for.
     * @param   boolean $notNullUrl Originally remote thumbnails have a URL stored, we use this to find the "original"
     *
     * @return  File_thumbnail
     * @throws  NoResultException if no File_thumbnail matched the criteria
     */
    static function byFile(File $file, $notNullUrl=true) {
        $thumb = new File_thumbnail();
        $thumb->file_id = $file->getID();
        if ($notNullUrl) {
            $thumb->whereAdd('url IS NOT NULL');
        }
        $thumb->orderBy('modified ASC');    // the first created, a somewhat ugly hack
        $thumb->limit(1);
        if (!$thumb->find(true)) {
            throw new NoResultException($thumb);
        }
        return $thumb;
    }

    /**
     * Save a thumbnail record for the referenced file record.
     *
     * FIXME: Add error handling
     *
     * @param int $file_id
     * @param string $url
     * @param int $width
     * @param int $height
     */
    static function saveThumbnail($file_id, $url, $width, $height, $filename=null)
    {
        $tn = new File_thumbnail;
        $tn->file_id = $file_id;
        $tn->url = $url;
        $tn->filename = $filename;
        $tn->width = intval($width);
        $tn->height = intval($height);
        $tn->insert();
        return $tn;
    }

    static function path($filename)
    {
        File::tryFilename($filename);

        // NOTE: If this is left empty in default config, it will be set to File::path('thumb')
        $dir = common_config('thumbnail', 'dir');

        if (!in_array($dir[mb_strlen($dir)-1], ['/', '\\'])) {
            $dir .= DIRECTORY_SEPARATOR;
        }

        return $dir . $filename;
    }

    static function url($filename)
    {
        File::tryFilename($filename);

        // FIXME: private site thumbnails?

        $path = common_config('thumbnail', 'path');
        if (empty($path)) {
            return File::url('thumb')."/{$filename}";
        }

        $protocol = (GNUsocial::useHTTPS() ? 'https' : 'http');
        $server = common_config('thumbnail', 'server') ?: common_config('site', 'server');

        if ($path[mb_strlen($path)-1] != '/') {
            $path .= '/';
        }
        if ($path[0] != '/') {
            $path = '/'.$path;
        }

        return $protocol.'://'.$server.$path.$filename;
    }

    public function getFilename()
    {
        return File::tryFilename($this->filename);
    }

    /**
     *
     * @return  string  full filesystem path to the locally stored thumbnail file
     * @throws
     */
    public function getPath()
    {
        $oldpath = File::path($this->getFilename());
        $thumbpath = self::path($this->getFilename());

        // If we have a file in our old thumbnail storage path, move (or copy) it to the new one
        // (if the if/elseif don't match, we have a $thumbpath just as we should and can return it)
        if (file_exists($oldpath) && !file_exists($thumbpath)) {
            try {
                // let's get the filename of the File, to check below if it happens to be identical
                $file_filename = $this->getFile()->getFilename();
            } catch (NoResultException $e) {
                // reasonably the function calling us will handle the following as "File_thumbnail entry should be deleted"
                throw new FileNotFoundException($thumbpath);
            } catch (InvalidFilenameException $e) {
                // invalid filename in getFile()->getFilename(), just
                // means the File object isn't stored locally and that
                // means it's safe to move it below.
                $file_filename = null;
            }

            if ($this->getFilename() === $file_filename) {
                // special case where thumbnail file exactly matches stored File filename
                common_debug('File filename and File_thumbnail filename match on '.$this->file_id.', copying instead');
                copy($oldpath, $thumbpath);
            } elseif (!rename($oldpath, $thumbpath)) {
                common_log(LOG_ERR, 'Could not move thumbnail from '._ve($oldpath).' to '._ve($thumbpath));
                throw new ServerException('Could not move thumbnail from old path to new path.');
            } else {
                common_log(LOG_DEBUG, 'Moved thumbnail '.$this->file_id.' from '._ve($oldpath).' to '._ve($thumbpath));
            }
        } elseif (!file_exists($thumbpath)) {
            throw new FileNotFoundException($thumbpath);
        }

        return $thumbpath;
    }

    public function getUrl()
    {
        if (!empty($this->filename) || $this->getFile()->isLocal()) {
            // A locally stored File, so we can dynamically generate a URL.
            $url = common_local_url('attachment_thumbnail', array('attachment'=>$this->file_id));
            if (strpos($url, '?') === false) {
                $url .= '?';
            }
            return $url . http_build_query(array('w'=>$this->width, 'h'=>$this->height));
        }

        // No local filename available, return the remote URL we have stored
        return $this->url;
    }

    public function getHeight()
    {
        return $this->height;
    }

    public function getWidth()
    {
        return $this->width;
    }

    /**
     * @throws UseFileAsThumbnailException from File_thumbnail->getUrl() for stuff like animated GIFs
     */
    public function getHtmlAttrs(array $orig=array(), $overwrite=true)
    {
        $attrs = [
                'height' => $this->getHeight(),
                'width'  => $this->getWidth(),
                'src'    => $this->getUrl(),
            ];
        return $overwrite ? array_merge($orig, $attrs) : array_merge($attrs, $orig);
    }

    public function delete($useWhere=false)
    {
        try {
            $thumbpath = self::path($this->getFilename());
            // if file does not exist, try to delete it
            $deleted = !file_exists($thumbpath) || @unlink($thumbpath);
            if (!$deleted) {
                common_log(LOG_ERR, 'Could not unlink existing thumbnail file: '._ve($thumbpath));
            }
        } catch (InvalidFilenameException $e) {
            common_log(LOG_ERR, 'Deleting object but not attempting deleting file: '._ve($e->getMessage()));
        }

        return parent::delete($useWhere);
    }

    public function getFile()
    {
        return File::getByID($this->file_id);
    }

    public function getFileId()
    {
        return $this->file_id;
    }

    static public function hashurl($url)
    {
        if (!mb_strlen($url)) {
            throw new Exception('No URL provided to hash algorithm.');
        }
        return hash(self::URLHASH_ALG, $url);
    }

    public function onInsert()
    {
        $this->setUrlhash();
    }

    public function onUpdate($dataObject=false)
    {
        // if we have nothing to compare with OR it has changed from previous entry
        if (!$dataObject instanceof Managed_DataObject || $this->url !== $dataObject->url) {
            $this->setUrlhash();
        }
    }

    public function setUrlhash()
    {
        $this->urlhash = mb_strlen($this->url)>0 ? self::hashurl($this->url) : null;
    }
}


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

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

/**
 * Table Definition for file_to_post
 */

class File_to_post extends Managed_DataObject
{
    ###START_AUTOCODE
    /* the code below is auto generated do not remove the above tag */

    public $__table = 'file_to_post';                    // table name
    public $file_id;                         // int(4)  primary_key not_null
    public $post_id;                         // int(4)  primary_key not_null
    public $modified;                        // timestamp()   not_null default_CURRENT_TIMESTAMP

    /* the code above is auto generated do not remove the tag below */
    ###END_AUTOCODE

    public static function schemaDef()
    {
        return array(
            'fields' => array(
                'file_id' => array('type' => 'int', 'not null' => true, 'description' => 'id of URL/file'),
                'post_id' => array('type' => 'int', 'not null' => true, 'description' => 'id of the notice it belongs to'),
                'modified' => array('type' => 'timestamp', 'not null' => true, 'description' => 'date this record was modified'),
            ),
            'primary key' => array('file_id', 'post_id'),
            'foreign keys' => array(
                'file_to_post_file_id_fkey' => array('file', array('file_id' => 'id')),
                'file_to_post_post_id_fkey' => array('notice', array('post_id' => 'id')),
            ),
            'indexes' => array(
                'file_id_idx' => array('file_id'),
                'post_id_idx' => array('post_id'),
            ),
        );
    }

    static function processNew(File $file, Notice $notice) {
        static $seen = array();

        $file_id = $file->getID();
        $notice_id = $notice->getID();
        if (!array_key_exists($notice_id, $seen)) {
            $seen[$notice_id] = array();
        }

        if (empty($seen[$notice_id]) || !in_array($file_id, $seen[$notice_id])) {
            try {
                $f2p = File_to_post::getByPK(array('post_id' => $notice_id,
                                                   'file_id' => $file_id));
            } catch (NoResultException $e) {
                $f2p = new File_to_post;
                $f2p->file_id = $file_id;
                $f2p->post_id = $notice_id;
                $f2p->insert();

                $file->blowCache();
            }

            $seen[$notice_id][] = $file_id;
        }
    }

    static function getNoticeIDsByFile(File $file)
    {
        $f2p = new File_to_post();

        $f2p->selectAdd();
        $f2p->selectAdd('post_id');

        $f2p->file_id = $file->getID();

        $ids = array();

        if (!$f2p->find()) {
            throw new NoResultException($f2p);
        }

        return $f2p->fetchAll('post_id');
    }

    function delete($useWhere=false)
    {
        try {
            $f = File::getByID($this->file_id);
            $f->blowCache();
        } catch (NoResultException $e) {
            // ...alright, that's weird, but no File to delete anyway.
        }

        return parent::delete($useWhere);
    }
}


code:
<?php
/**
 * Table Definition for foreign_link
 */
require_once INSTALLDIR.'/classes/Memcached_DataObject.php';

class Foreign_link extends Managed_DataObject
{
    ###START_AUTOCODE
    /* the code below is auto generated do not remove the above tag */

    public $__table = 'foreign_link';                    // table name
    public $user_id;                         // int(4)  primary_key not_null
    public $foreign_id;                      // bigint(8)  primary_key not_null unsigned
    public $service;                         // int(4)  primary_key not_null
    public $credentials;                     // varchar(191)   not 255 because utf8mb4 takes more space
    public $noticesync;                      // tinyint(1)   not_null default_1
    public $friendsync;                      // tinyint(1)   not_null default_2
    public $profilesync;                     // tinyint(1)   not_null default_1
    public $last_noticesync;                 // datetime()
    public $last_friendsync;                 // datetime()
    public $created;                         // datetime()   not_null
    public $modified;                        // timestamp()   not_null default_CURRENT_TIMESTAMP

    /* the code above is auto generated do not remove the tag below */
    ###END_AUTOCODE

    public static function schemaDef()
    {
        return array(
            'fields' => array(
                'user_id' => array('type' => 'int', 'not null' => true, 'description' => 'link to user on this system, if exists'),
                'foreign_id' => array('type' => 'int', 'size' => 'big', 'unsigned' => true, 'not null' => true, 'description' => 'link to user on foreign service, if exists'),
                'service' => array('type' => 'int', 'not null' => true, 'description' => 'foreign key to service'),
                'credentials' => array('type' => 'varchar', 'length' => 191, 'description' => 'authc credentials, typically a password'),
                'noticesync' => array('type' => 'int', 'size' => 'tiny', 'not null' => true, 'default' => 1, 'description' => 'notice synchronization, bit 1 = sync outgoing, bit 2 = sync incoming, bit 3 = filter local replies'),
                'friendsync' => array('type' => 'int', 'size' => 'tiny', 'not null' => true, 'default' => 2, 'description' => 'friend synchronization, bit 1 = sync outgoing, bit 2 = sync incoming'),
                'profilesync' => array('type' => 'int', 'size' => 'tiny', 'not null' => true, 'default' => 1, 'description' => 'profile synchronization, bit 1 = sync outgoing, bit 2 = sync incoming'),
                'last_noticesync' => array('type' => 'datetime', 'description' => 'last time notices were imported'),
                'last_friendsync' => array('type' => 'datetime', 'description' => 'last time friends were imported'),
                'created' => array('type' => 'datetime', 'not null' => true, 'description' => 'date this record was created'),
                'modified' => array('type' => 'timestamp', 'not null' => true, 'description' => 'date this record was modified'),
            ),
            'primary key' => array('user_id', 'foreign_id', 'service'),
            'foreign keys' => array(
                'foreign_link_user_id_fkey' => array('user', array('user_id' => 'id')),
                'foreign_link_foreign_id_fkey' => array('foreign_user', array('foreign_id' => 'id', 'service' => 'service')),
                'foreign_link_service_fkey' => array('foreign_service', array('service' => 'id')),
            ),
            'indexes' => array(
                'foreign_user_user_id_idx' => array('user_id'),
            ),
        );
    }

    static function getByUserID($user_id, $service)
    {
        if (empty($user_id) || empty($service)) {
            throw new ServerException('Empty user_id or service for Foreign_link::getByUserID');
        }

        $flink = new Foreign_link();
        $flink->service = $service;
        $flink->user_id = $user_id;
        $flink->limit(1);

        if (!$flink->find(true)) {
            throw new NoResultException($flink);
        }

        return $flink;
    }

    static function getByForeignID($foreign_id, $service)
    {
        if (empty($foreign_id) || empty($service)) {
            throw new ServerException('Empty foreign_id or service for Foreign_link::getByForeignID');
        }

        $flink = new Foreign_link();
        $flink->service = $service;
        $flink->foreign_id = $foreign_id;
        $flink->limit(1);

        if (!$flink->find(true)) {
            throw new NoResultException($flink);
        }

        return $flink;
    }

    function set_flags($noticesend, $noticerecv, $replysync, $repeatsync, $friendsync)
    {
        if ($noticesend) {
            $this->noticesync |= FOREIGN_NOTICE_SEND;
        } else {
            $this->noticesync &= ~FOREIGN_NOTICE_SEND;
        }

        if ($noticerecv) {
            $this->noticesync |= FOREIGN_NOTICE_RECV;
        } else {
            $this->noticesync &= ~FOREIGN_NOTICE_RECV;
        }

        if ($replysync) {
            $this->noticesync |= FOREIGN_NOTICE_SEND_REPLY;
        } else {
            $this->noticesync &= ~FOREIGN_NOTICE_SEND_REPLY;
        }

        if ($repeatsync) {
            $this->noticesync |= FOREIGN_NOTICE_SEND_REPEAT;
        } else {
            $this->noticesync &= ~FOREIGN_NOTICE_SEND_REPEAT;
        }

        if ($friendsync) {
            $this->friendsync |= FOREIGN_FRIEND_RECV;
        } else {
            $this->friendsync &= ~FOREIGN_FRIEND_RECV;
        }

        $this->profilesync = 0;
    }

    // Convenience methods
    function getForeignUser()
    {
        $fuser = new Foreign_user();
        $fuser->service = $this->service;
        $fuser->id = $this->foreign_id;

        $fuser->limit(1);

        if (!$fuser->find(true)) {
            throw new NoResultException($fuser);
        }

        return $fuser;
    }

    function getUser()
    {
        return Profile::getByID($this->user_id)->getUser();
    }

    function getProfile()
    {
        return Profile::getByID($this->user_id);
    }

    // Make sure we only ever delete one record at a time
    function safeDelete()
    {
        if (!empty($this->user_id)
            && !empty($this->foreign_id)
            && !empty($this->service))
        {
            return $this->delete();
        } else {
            common_debug(LOG_WARNING,
                'Foreign_link::safeDelete() tried to delete a '
                . 'Foreign_link without a fully specified compound key: '
                . var_export($this, true));
            return false;
        }
    }
}


code:
<?php
/**
 * Table Definition for foreign_service
 */
require_once INSTALLDIR.'/classes/Memcached_DataObject.php';

class Foreign_service extends Managed_DataObject
{
    ###START_AUTOCODE
    /* the code below is auto generated do not remove the above tag */

    public $__table = 'foreign_service';                 // table name
    public $id;                              // int(4)  primary_key not_null
    public $name;                            // varchar(32)  unique_key not_null
    public $description;                     // varchar(191)   not 255 because utf8mb4 takes more space
    public $created;                         // datetime()   not_null
    public $modified;                        // timestamp()   not_null default_CURRENT_TIMESTAMP

    /* the code above is auto generated do not remove the tag below */
    ###END_AUTOCODE

    public static function schemaDef()
    {
        return array(
            'fields' => array(
                'id' => array('type' => 'int', 'not null' => true, 'description' => 'numeric key for service'),
                'name' => array('type' => 'varchar', 'length' => 32, 'not null' => true, 'description' => 'name of the service'),
                'description' => array('type' => 'varchar', 'length' => 191, 'description' => 'description'),
                'created' => array('type' => 'datetime', 'not null' => true, 'description' => 'date this record was created'),
                'modified' => array('type' => 'timestamp', 'not null' => true, 'description' => 'date this record was modified'),
            ),
            'primary key' => array('id'),
            'unique keys' => array(
                'foreign_service_name_key' => array('name'),
            ),
        );
    }
}


code:
<?php
/**
 * Table Definition for foreign_subscription
 */
require_once INSTALLDIR.'/classes/Memcached_DataObject.php';

class Foreign_subscription extends Managed_DataObject
{
    ###START_AUTOCODE
    /* the code below is auto generated do not remove the above tag */

    public $__table = 'foreign_subscription';            // table name
    public $service;                         // int(4)  primary_key not_null
    public $subscriber;                      // int(4)  primary_key not_null
    public $subscribed;                      // int(4)  primary_key not_null
    public $created;                         // datetime()   not_null

    /* the code above is auto generated do not remove the tag below */
    ###END_AUTOCODE

    public static function schemaDef()
    {
        return array(

            'fields' => array(
                'service' => array('type' => 'int', 'not null' => true, 'description' => 'service where relationship happens'),
                'subscriber' => array('type' => 'int', 'size' => 'big', 'not null' => true, 'description' => 'subscriber on foreign service'),
                'subscribed' => array('type' => 'int', 'size' => 'big', 'not null' => true, 'description' => 'subscribed user'),
                'created' => array('type' => 'datetime', 'not null' => true, 'description' => 'date this record was created'),
            ),
            'primary key' => array('service', 'subscriber', 'subscribed'),
            'foreign keys' => array(
                'foreign_subscription_service_fkey' => array('foreign_service', array('service' => 'id')),
                'foreign_subscription_subscriber_fkey' => array('foreign_user', array('subscriber' => 'id', 'service' => 'service')),
                'foreign_subscription_subscribed_fkey' => array('foreign_user', array('subscribed' => 'id', 'service' => 'service')),
            ),
            'indexes' => array(
                'foreign_subscription_subscriber_idx' => array('service', 'subscriber'),
                'foreign_subscription_subscribed_idx' => array('service', 'subscribed'),
            ),
        );
    }
}


code:
<?php
/**
 * Table Definition for foreign_user
 */
require_once INSTALLDIR.'/classes/Memcached_DataObject.php';

class Foreign_user extends Managed_DataObject
{
    ###START_AUTOCODE
    /* the code below is auto generated do not remove the above tag */

    public $__table = 'foreign_user';                    // table name
    public $id;                              // bigint(8)  primary_key not_null
    public $service;                         // int(4)  primary_key not_null
    public $uri;                             // varchar(191)  unique_key not_null   not 255 because utf8mb4 takes more space
    public $nickname;                        // varchar(191)   not 255 because utf8mb4 takes more space
    public $created;                         // datetime()   not_null
    public $modified;                        // timestamp()   not_null default_CURRENT_TIMESTAMP

    /* the code above is auto generated do not remove the tag below */
    ###END_AUTOCODE

    public static function schemaDef()
    {
        return array(
            'fields' => array(
                'id' => array('type' => 'int', 'size' => 'big', 'not null' => true, 'description' => 'unique numeric key on foreign service'),
                'service' => array('type' => 'int', 'not null' => true, 'description' => 'foreign key to service'),
                'uri' => array('type' => 'varchar', 'length' => 191, 'not null' => true, 'description' => 'identifying URI'),
                'nickname' => array('type' => 'varchar', 'length' => 191, 'description' => 'nickname on foreign service'),
                'created' => array('type' => 'datetime', 'not null' => true, 'description' => 'date this record was created'),
                'modified' => array('type' => 'timestamp', 'not null' => true, 'description' => 'date this record was modified'),
            ),
            'primary key' => array('id', 'service'),
            'foreign keys' => array(
                'foreign_user_service_fkey' => array('foreign_service', array('service' => 'id')),
            ),
            'unique keys' => array(
                'foreign_user_uri_key' => array('uri'),
            ),
        );
    }

    static function getForeignUser($id, $service)
    {
        if (empty($id) || empty($service)) {
            throw new ServerException('Empty foreign user id or service for Foreign_user::getForeignUser');
        }

        $fuser = new Foreign_user();
        $fuser->id      = $id;
        $fuser->service = $service;
        $fuser->limit(1);

        if (!$fuser->find(true)) {
            throw new NoResultException($fuser);
        }

        return $fuser;
    }

    static function getByNickname($nickname, $service)
    {
        if (empty($nickname) || empty($service)) {
            throw new ServerException('Empty nickname or service for Foreign_user::getByNickname');
        }

        $fuser = new Foreign_user();
        $fuser->service = $service;
        $fuser->nickname = $nickname;
        $fuser->limit(1);

        if (!$fuser->find(true)) {
            throw new NoResultException($fuser);
        }

        return $fuser;
    }
}


code:
<?php
if (!defined('GNUSOCIAL')) { exit(1); }

class GS_DataObject extends DB_DataObject
{
    public function _autoloadClass($class, $table=false)
    {
        // avoid those annoying PEAR::DB strict standards warnings it causes
        $old = error_reporting();
        error_reporting(error_reporting() & ~E_STRICT);

        $res = parent::_autoloadClass($class, $table);

        // reset
        error_reporting($old);
        return $res;
    }

    // wraps the _connect call so we don't throw E_STRICT warnings during it
    public function _connect()
    {
        // avoid those annoying PEAR::DB strict standards warnings it causes
        $old = error_reporting();
        error_reporting(error_reporting() & ~E_STRICT);

        $res = parent::_connect();

        // reset
        error_reporting($old);
        return $res;
    }

    // wraps the _loadConfig call so we don't throw E_STRICT warnings during it
    // doesn't actually return anything, but we'll follow the same model as the rest of the wrappers
    public function _loadConfig()
    {
        // avoid those annoying PEAR::DB strict standards warnings it causes
        $old = error_reporting();
        error_reporting(error_reporting() & ~E_STRICT);

        $res = parent::_loadConfig();

        // reset
        error_reporting($old);
        return $res;
    }

    // wraps the count call so we don't throw E_STRICT warnings during it
    public function count($countWhat = false,$whereAddOnly = false)
    {
        // avoid those annoying PEAR::DB strict standards warnings it causes
        $old = error_reporting();
        error_reporting(error_reporting() & ~E_STRICT);

        $res = parent::count($countWhat, $whereAddOnly);

        // reset
        error_reporting($old);
        return $res;
    }

    static public function debugLevel($v = null)
    {
        // avoid those annoying PEAR::DB strict standards warnings it causes
        $old = error_reporting();
        error_reporting(error_reporting() & ~E_STRICT);

        $res = parent::debugLevel($v);

        // reset
        error_reporting($old);
        return $res;
    }

    // delete calls PEAR::isError from DB_DataObject, so let's make that disappear too
    public function delete($useWhere = false)
    {
        // avoid those annoying PEAR::DB strict standards warnings it causes
        $old = error_reporting();
        error_reporting(error_reporting() & ~E_STRICT);

        $res = parent::delete($useWhere);

        // reset
        error_reporting($old);
        return $res;
    }

    static public function factory($table = '')
    {
        // avoid those annoying PEAR::DB strict standards warnings it causes
        $old = error_reporting();
        error_reporting(error_reporting() & ~E_STRICT);

        $res = parent::factory($table);

        // reset
        error_reporting($old);
        return $res;
    }

    public function get($k = null, $v = null)
    {
        // avoid those annoying PEAR::DB strict standards warnings it causes
        $old = error_reporting();
        error_reporting(error_reporting() & ~E_STRICT);

        $res = parent::get($k, $v);

        // reset
        error_reporting($old);
        return $res;
    }

    public function fetch()
    {
        // avoid those annoying PEAR::DB strict standards warnings it causes
        $old = error_reporting();
        error_reporting(error_reporting() & ~E_STRICT);

        $res = parent::fetch();

        // reset
        error_reporting($old);
        return $res;
    }

    public function find($n = false)
    {
        // avoid those annoying PEAR::DB strict standards warnings it causes
        $old = error_reporting();
        error_reporting(error_reporting() & ~E_STRICT);

        $res = parent::find($n);

        // reset
        error_reporting($old);
        return $res;
    }

    public function fetchRow($row = null)
    {
        // avoid those annoying PEAR::DB strict standards warnings it causes
        $old = error_reporting();
        error_reporting(error_reporting() & ~E_STRICT);

        $res = parent::fetchRow($row);

        // reset
        error_reporting($old);
        return $res;
    }

    // insert calls PEAR::isError from DB_DataObject, so let's make that disappear too
    public function insert()
    {
        // avoid those annoying PEAR::DB strict standards warnings it causes
        $old = error_reporting();
        error_reporting(error_reporting() & ~E_STRICT);

        $res = parent::insert();

        // reset
        error_reporting($old);
        return $res;
    }

    // DB_DataObject's joinAdd calls DB_DataObject::factory explicitly, so our factory-override doesn't work
    public function joinAdd($obj = false, $joinType='INNER', $joinAs=false, $joinCol=false)
    {
        // avoid those annoying PEAR::DB strict standards warnings it causes
        $old = error_reporting();
        error_reporting(error_reporting() & ~E_STRICT);

        $res = parent::joinAdd($obj, $joinType, $joinAs, $joinCol);

        // reset
        error_reporting($old);
        return $res;
    }

    public function links()
    {
        // avoid those annoying PEAR::DB strict standards warnings it causes
        $old = error_reporting();
        error_reporting(error_reporting() & ~E_STRICT);

        $res = parent::links();

        // reset
        error_reporting($old);
        return $res;
    }

    // wraps the update call so we don't throw E_STRICT warnings during it
    public function update($dataObject = false)
    {
        // avoid those annoying PEAR::DB strict standards warnings it causes
        $old = error_reporting();
        error_reporting(error_reporting() & ~E_STRICT);

        $res = parent::update($dataObject);

        // reset
        error_reporting($old);
        return $res;
    }

    static public function staticGet($class, $k, $v = null)
    {
        // avoid those annoying PEAR::DB strict standards warnings it causes
        $old = error_reporting();
        error_reporting(error_reporting() & ~E_STRICT);

        $res = parent::staticGet($class, $k, $v);

        // reset
        error_reporting($old);
        return $res;
    }

    public function staticGetAutoloadTable($table)
    {
        // avoid those annoying PEAR::DB strict standards warnings it causes
        $old = error_reporting();
        error_reporting(error_reporting() & ~E_STRICT);

        $res = parent::staticGetAutoloadTable($table);

        // reset
        error_reporting($old);
        return $res;
    }
}


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

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

require_once INSTALLDIR.'/classes/Memcached_DataObject.php';

class Group_alias extends Managed_DataObject
{
    ###START_AUTOCODE
    /* the code below is auto generated do not remove the above tag */

    public $__table = 'group_alias';                     // table name
    public $alias;                           // varchar(64)  primary_key not_null
    public $group_id;                        // int(4)   not_null
    public $modified;                        // timestamp()   not_null default_CURRENT_TIMESTAMP

    /* the code above is auto generated do not remove the tag below */
    ###END_AUTOCODE

    public static function schemaDef()
    {
        return array(
            'fields' => array(
                'alias' => array('type' => 'varchar', 'length' => 64, 'not null' => true, 'description' => 'additional nickname for the group'),
                'group_id' => array('type' => 'int', 'not null' => true, 'description' => 'group profile is blocked from'),
                'modified' => array('type' => 'timestamp', 'not null' => true, 'description' => 'date alias was created'),
            ),
            'primary key' => array('alias'),
            'foreign keys' => array(
                'group_alias_group_id_fkey' => array('user_group', array('group_id' => 'id')),
            ),
            'indexes' => array(
                'group_alias_group_id_idx' => array('group_id'),
            ),
        );
    }

    public function getProfile()
    {
        $group = User_group::getKV('id', $this->group_id);
        if (!($group instanceof User_group)) {
            return null;    // TODO: Throw exception when other code is ready
        }
        return $group->getProfile();
    }
}


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

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

require_once INSTALLDIR.'/classes/Memcached_DataObject.php';

class Group_block extends Managed_DataObject
{
    ###START_AUTOCODE
    /* the code below is auto generated do not remove the above tag */

    public $__table = 'group_block';                     // table name
    public $group_id;                        // int(4)  primary_key not_null
    public $blocked;                         // int(4)  primary_key not_null
    public $blocker;                         // int(4)   not_null
    public $modified;                        // timestamp()   not_null default_CURRENT_TIMESTAMP

    /* the code above is auto generated do not remove the tag below */
    ###END_AUTOCODE

    public static function schemaDef()
    {
        return array(
            'fields' => array(
                'group_id' => array('type' => 'int', 'not null' => true, 'description' => 'group profile is blocked from'),
                'blocked' => array('type' => 'int', 'not null' => true, 'description' => 'profile that is blocked'),
                'blocker' => array('type' => 'int', 'not null' => true, 'description' => 'user making the block'),
                'modified' => array('type' => 'timestamp', 'not null' => true, 'description' => 'date of blocking'),
            ),
            'primary key' => array('group_id', 'blocked'),
            'foreign keys' => array(
                'group_block_group_id_fkey' => array('user_group', array('group_id' => 'id')),
                'group_block_blocked_fkey' => array('profile', array('blocked' => 'id')),
                'group_block_blocker_fkey' => array('user', array('blocker' => 'id')),
            ),
        );
    }

    static function isBlocked($group, $profile)
    {
        $block = Group_block::pkeyGet(array('group_id' => $group->id,
                                            'blocked' => $profile->id));
        return !empty($block);
    }

    static function blockProfile($group, $profile, $blocker)
    {
        // Insert the block

        $block = new Group_block();

        $block->query('BEGIN');

        $block->group_id = $group->id;
        $block->blocked  = $profile->id;
        $block->blocker  = $blocker->id;

        $result = $block->insert();

        if ($result === false) {
            common_log_db_error($block, 'INSERT', __FILE__);
            return null;
        }

        // Delete membership if any

        $member = new Group_member();

        $member->group_id   = $group->id;
        $member->profile_id = $profile->id;

        if ($member->find(true)) {
            $result = $member->delete();
            if ($result === false) {
                common_log_db_error($member, 'DELETE', __FILE__);
                return null;
            }
        }

        // Commit, since both have been done

        $block->query('COMMIT');

        return $block;
    }

    static function unblockProfile($group, $profile)
    {
        $block = Group_block::pkeyGet(array('group_id' => $group->id,
                                            'blocked' => $profile->id));

        if (empty($block)) {
            return null;
        }

        $result = $block->delete();

        if (!$result) {
            common_log_db_error($block, 'DELETE', __FILE__);
            return null;
        }

        return true;
    }
}


code:
<?php

/**
 * Table Definition for group_inbox
 */
class Group_inbox extends Managed_DataObject
{
    ###START_AUTOCODE
    /* the code below is auto generated do not remove the above tag */

    public $__table = 'group_inbox';                     // table name
    public $group_id;                        // int(4)  primary_key not_null
    public $notice_id;                       // int(4)  primary_key not_null
    public $created;                         // datetime()   not_null

    /* the code above is auto generated do not remove the tag below */
    ###END_AUTOCODE

    public static function schemaDef()
    {
        return array(
            'description' => 'Many-many table listing notices posted to a given group, or which groups a given notice was posted to.',
            'fields' => array(
                'group_id' => array('type' => 'int', 'not null' => true, 'description' => 'group receiving the message'),
                'notice_id' => array('type' => 'int', 'not null' => true, 'description' => 'notice received'),
                'created' => array('type' => 'datetime', 'not null' => true, 'description' => 'date the notice was created'),
            ),
            'primary key' => array('group_id', 'notice_id'),
            'foreign keys' => array(
                'group_inbox_group_id_fkey' => array('user_group', array('group_id' => 'id')),
                'group_inbox_notice_id_fkey' => array('notice', array('notice_id' => 'id')),
            ),
            'indexes' => array(
                'group_inbox_created_idx' => array('created'),
                'group_inbox_notice_id_idx' => array('notice_id'),
                'group_inbox_group_id_created_notice_id_idx' => array('group_id', 'created', 'notice_id'),
            ),
        );
    }
}