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

/**
 * @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   https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
 */

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, '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 a local attachment url, don't save a new file record.
        $uh = parse_url($given_url, PHP_URL_HOST);
        $up = parse_url($given_url, PHP_URL_PATH);
        if ($uh == common_config('site', 'server') || $uh == common_config('attachments', 'server')) {
            unset($uh);
            $r = Router::get();
            // Skip the / in the beginning or $r->map won't match
            try {
                $args = $r->map(mb_substr($up, 1));
                if ($args['action'] === 'attachment'          ||
                    $args['action'] === 'attachment_view'     ||
                    $args['action'] === 'attachment_download' ||
                    $args['action'] === 'attachment_thumbnail' ) {
                    try {
                        if (array_key_exists('attachment', $args)) {
                            return File::getByID((int)$args['attachment']);
                        } elseif (array_key_exists('filehash', $args)) {
                            $file = File::getByHash($args['filehash']);
                            $file->fetch();
                            return $file;
                        }
                    } 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 = (int)$redir_data['size'];
        }
        if (isset($redir_data['time']) && $redir_data['time'] > 0) {
            $file->date = (int)$redir_data['time'];
        }
        $file->saveFile();
        return $file;
    }

    public function saveFile()
    {
        $this->urlhash = is_null($this->url) ? null : 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|null $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, bool $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
                       INNER JOIN file_to_post
                              ON file_to_post.file_id = file.id
                       INNER JOIN notice
                              ON file_to_post.post_id = notice.id
                  WHERE profile_id = {$scoped->id} AND
                        filename IS NULL AND
                        file.url IS NOT NULL";
        $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 CURRENT_DATE)'
                . ' AND EXTRACT(YEAR  FROM file.modified) = EXTRACT(YEAR  FROM CURRENT_DATE)';
        $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(): int
    {
        return (int)$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 null|string|bool Value from the 'extblacklist' array, in the config
     * @throws ServerException
     */
    public static function getSafeExtension(string $filename)
    {
        if (preg_match('/^.+?\.([A-Za-z0-9]+)$/', $filename, $matches) === 1) {
            // 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])) {
                    // Blocked
                    return false;
                }
                // return a safe replacement extension ('php' => 'phps' for example)
                return $blacklist[$ext];
            } else {
                // the attachment extension based on its filename was not blacklisted so it's ok to use it
                return $ext;
            }
        } else {
            // No extension
            return null;
        }
    }

    /**
     * @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
     * @throws ServerException
     */
    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 = self::getSafeExtension($filename);
                if ($ext === false) {
                    // we don't have a safe replacement extension
                    throw new ClientException(_m('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 mixed $filename
     * @return false|int
     */
    public static function validFilename($filename)
    {
        return preg_match('/^[A-Za-z0-9._-]+$/', $filename);
    }

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

    /**
     * Construct a path
     *
     * @param mixed $filename Will be tested by tryFilename
     * @param string|null $dir Attachments directory by default
     * @param bool $test_filename
     * @return string
     * @throws InvalidFilenameException
     * @throws ServerException
     */
    public static function path($filename, ?string $dir = null, bool $test_filename = true)
    {
        if ($test_filename) {
            self::tryFilename($filename);
        }

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

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

        return $dir . $filename;
    }

    /**
     * Don't use for attachments, only for assets.
     *
     * @param $filename
     * @return mixed|string
     * @throws InvalidFilenameException
     * @throws ServerException
     */
    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($enclosure->url) && 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 or generate one.
     *
     * @param int|null $width    Max width of thumbnail in pixels. (if null, use common_config values)
     * @param int|null $height   Max height of thumbnail in pixels. (if null, square-crop to $width)
     * @param bool $crop         Crop to the max-values' aspect ratio
     * @param bool $force_still  Don't allow fallback to showing original (such as animated GIF)
     * @param bool|null $upscale Whether or not to scale smaller images up to larger thumbnail sizes. (null = site default)
     *
     * @return File_thumbnail
     *
     * @throws ClientException
     * @throws FileNotFoundException
     * @throws FileNotStoredLocallyException
     * @throws InvalidFilenameException
     * @throws NoResultException
     * @throws ServerException on various other errors
     * @throws UnsupportedMediaException if, despite trying, we can't understand how to make a thumbnail for this format
     * @throws UseFileAsThumbnailException if the file is considered an image itself and should be itself as thumbnail
     */
    public function getThumbnail (?int $width = null, ?int $height = null, bool $crop = false, bool $force_still = true, ?bool $upscale = null): File_thumbnail
    {
        return File_thumbnail::fromFileObject($this, $width, $height, $crop, $force_still, $upscale);
    }

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

    /**
     * Returns the path to either a file, or it's thumbnail if the file doesn't exist.
     * This is useful in case the original file is deleted, or, as is the case for Embed
     * thumbnails, we only have a thumbnail and not a file
     * @param File_thumbnail|null $thumbnail
     * @return string Path
     * @throws FileNotFoundException
     * @throws FileNotStoredLocallyException
     * @throws InvalidFilenameException
     * @throws ServerException
     */
    public function getFileOrThumbnailPath(?File_thumbnail $thumbnail = null): string
    {
        if (!empty($thumbnail)) {
            return $thumbnail->getPath();
        }
        if (!empty($this->filename)) {
            $filepath = self::path($this->filename);
            if (file_exists($filepath)) {
                return $filepath;
            } else {
                throw new FileNotFoundException($filepath);
            }
        } else {
            try {
                return File_thumbnail::byFile($this, true)->getPath();
            } catch (NoResultException $e) {
                // File not stored locally
                throw new FileNotStoredLocallyException($this);
            }
        }
    }

    /**
     * Return the mime type of the thumbnail if we have it, or, if not, of the File
     * @param File_thumbnail|null $thumbnail
     * @return string
     * @throws FileNotFoundException
     * @throws NoResultException
     * @throws ServerException
     * @throws UnsupportedMediaException
     * @throws Exception
     */
    public function getFileOrThumbnailMimetype(?File_thumbnail $thumbnail = null) : string
    {
        if (!empty($thumbnail)) {
            $filepath = $thumbnail->getPath();
        } elseif (!empty($this->filename)) {
            return $this->mimetype;
        } else {
            $filepath = File_thumbnail::byFile($this, true)->getPath();
        }

        $info = @getimagesize($filepath);
        if ($info !== false) {
            return $info['mime'];
        } else {
            throw new UnsupportedMediaException(_m("Thumbnail is not an image."));
        }
    }

    /**
     * Return the size of the thumbnail if we have it, or, if not, of the File
     * @param File_thumbnail|null $thumbnail
     * @return int
     * @throws FileNotFoundException
     * @throws NoResultException
     * @throws ServerException
     */
    public function getFileOrThumbnailSize(?File_thumbnail $thumbnail = null) : int
    {
        if (!empty($thumbnail)) {
            return filesize($thumbnail->getPath());
        } elseif (!empty($this->filename)) {
            return $this->getSize();
        } else {
            return filesize(File_thumbnail::byFile($this)->getPath());
        }
    }

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

    public function getAttachmentDownloadUrl()
    {
        return common_local_url('attachment_download', ['filehash' => $this->filehash]);
    }

    public function getAttachmentViewUrl()
    {
        return common_local_url('attachment_view', ['filehash' => $this->filehash]);
    }

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

        // The original file's URL
        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()) {
            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');
        }
        $result = $this->query(sprintf(
            <<<'END'
            UPDATE %1$s
              SET urlhash = %2$s, url = %3$s, modified = CURRENT_TIMESTAMP
              WHERE urlhash = %4$s;
            END,
            $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->url) && !empty($this->filename);
    }

    public function unlink() {
        // 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)));
            }
        }
    }

    public function delete($useWhere=false)
    {
        // Delete the file, if it exists locally
        $this->unlink();

        // Clear out related things in the database and filesystem, such as thumbnails
        $related = [
            'File_redirection',
            'File_thumbnail',
            'File_to_post'
        ];
        Event::handle('FileDeleteRelated', [$this, &$related]);

        foreach ($related as $cls) {
            $inst = new $cls();
            $inst->file_id = $this->id;
            if ($inst->find()) {
                while ($inst->fetch()) {
                    $inst->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(*) FROM %1$s ' .
            'WHERE LENGTH(url) > 191 GROUP BY id, shortenedurl HAVING COUNT(*) > 1',
            common_database_tablename($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...";
        switch (common_config('db', 'type')) {
            case 'pgsql':
                $url_sha256 = 'encode(sha256(CAST("url" AS bytea)), \'hex\')';
                break;
            case 'mysql':
                $url_sha256 = 'sha2(`url`, 256)';
                break;
            default:
                throw new ServerException('Unknown DB type selected.');
        }
        $tablefix->query(sprintf(
            'UPDATE %1$s SET urlhash = %2$s, modified = CURRENT_TIMESTAMP;',
            $tablefix->escapedTableName(),
            $url_sha256
        ));
        echo "DONE.\n";
        echo "Resuming core schema upgrade...";
    }
}


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

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

/**
 * 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')),
            ),
            'indexes' => array(
                'file_redirection_file_id_idx' => array('file_id'),
            ),
        );
    }

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

    public 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
     */
    public 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
     */
    public 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
     */
    public 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
     */

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

    public 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
     */
    public 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;
    }

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

    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']) && 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'] = [
            'type'        => 'varchar',
            'length'      => 64,
            'not null'    => true,
            'description' => 'sha256 hash of the URL',
        ];
        $schemadef['fields']['url'] = [
            '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...";
        switch (common_config('db', 'type')) {
            case 'pgsql':
                $url_sha256 = 'encode(sha256(CAST("url" AS bytea)), \'hex\')';
                break;
            case 'mysql':
                $url_sha256 = 'sha2(`url`, 256)';
                break;
            default:
                throw new ServerException('Unknown DB type selected.');
        }
        $tablefix->query(sprintf(
            'UPDATE %1$s SET urlhash = %2$s, modified = CURRENT_TIMESTAMP;',
            $tablefix->escapedTableName(),
            $url_sha256
        ));
        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: ksuudilla/gnu

license: mit


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

/*
 * @copyright 2008-2009 StatusNet, Inc.
 * @license   https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
 */

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

/**
 * 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', 'not null' => true, 'description' => 'width of thumbnail'),
                'height' => array('type' => 'int', 'not null' => true, '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_urlhash_idx' => array('urlhash'),
            ),
            'foreign keys' => array(
                'file_thumbnail_file_id_fkey' => array('file', array('file_id' => 'id')),
            )
        );
    }

    /**
     * Get the attachment's thumbnail record, if any or generate one.
     *
     * @param File $file
     * @param int|null $width    Max width of thumbnail in pixels. (if null, use common_config values)
     * @param int|null $height   Max height of thumbnail in pixels. (if null, square-crop to $width)
     * @param bool $crop         Crop to the max-values' aspect ratio
     * @param bool $force_still  Don't allow fallback to showing original (such as animated GIF)
     * @param bool|null $upscale Whether or not to scale smaller images up to larger thumbnail sizes. (null = site default)
     *
     * @return File_thumbnail
     *
     * @throws ClientException
     * @throws FileNotFoundException
     * @throws FileNotStoredLocallyException
     * @throws InvalidFilenameException
     * @throws NoResultException
     * @throws ServerException on various other errors
     * @throws UnsupportedMediaException if, despite trying, we can't understand how to make a thumbnail for this format
     * @throws UseFileAsThumbnailException if the file is considered an image itself and should be itself as thumbnail
     */
    public static function fromFileObject(
        File $file,
        ?int $width = null,
        ?int $height = null,
        bool $crop = false,
        bool $force_still = true,
        ?bool $upscale = null
    ): File_thumbnail {
        if (is_null($file->filename)) {  // Remote file
            // If StoreRemoteMedia is enabled...
            if (Event::handle('CreateFileImageThumbnailSource', [$file, &$imgPath, 'image'])) {
                if (!file_exists($imgPath)) {
                    throw new FileNotFoundException($imgPath);
                }

                // First some mimetype specific exceptions
                switch ($file->mimetype) {
                    case 'image/svg+xml':
                        throw new UseFileAsThumbnailException($file);
                }
            }
            throw new FileNotFoundException("This remote file has no local thumbnail.");
        }
        $image = ImageFile::fromFileObject($file);
        $imgPath = $image->getPath();
        $media = common_get_mime_media($file->mimetype);
        if (Event::handle('CreateFileImageThumbnailSource', [$file, &$imgPath, $media])) {
            if (!file_exists($imgPath)) {
                throw new FileNotFoundException($imgPath);
            }

            // First some mimetype specific exceptions
            switch ($file->mimetype) {
                case 'image/svg+xml':
                    throw new UseFileAsThumbnailException($file);
            }
        }

        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($file);
                } catch (NoResultException $e) {
                    // and if it's not a remote file, it'll be safe to use the locally stored File
                    throw new UseFileAsThumbnailException($file);
                }
            }
        }

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

    /**
     * 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
            );
        } elseif ($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
     */
    public 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
     */
    public 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 = (int)$width;
        $tn->height = (int)$height;
        $tn->insert();
        return $tn;
    }

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

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

    /**
     * @return  string  full filesystem path to the locally stored thumbnail file
     * @throws FileNotFoundException
     * @throws ServerException
     */
    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()
    {
        $url = common_local_url('attachment_thumbnail', ['filehash' => $this->getFile()->filehash]);
        if (strpos($url, '?') === false) {
            $url .= '?';
        }
        return $url . http_build_query(['w'=>$this->width, 'h'=>$this->height]);
    }

    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(): File
    {
        return File::getByID($this->file_id);
    }

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

    public static 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
// This file is part of GNU social - https://www.gnu.org/software/social
//
// GNU social is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// GNU social is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with GNU social.  If not, see <http://www.gnu.org/licenses/>.

/**
 * Table Definition for file_to_post
 *
 * @copyright 2008, 2009 StatusNet, Inc.
 * @license   https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
 */

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

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_to_post_post_id_idx' => array('post_id'),
            ),
        );
    }

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

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

    public 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
// This file is part of GNU social - https://www.gnu.org/software/social
//
// GNU social is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// GNU social is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with GNU social.  If not, see <http://www.gnu.org/licenses/>.

/**
 * Table Definition for foreign_link
 */

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

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;                     // blob
    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()
    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', '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' => 'blob', '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', '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_service_fkey' => array('foreign_user', array('foreign_id' => 'id', 'service' => 'service')),
                'foreign_link_service_fkey' => array('foreign_service', array('service' => 'id')),
            ),
            'indexes' => array(
                'foreign_link_foreign_id_service_idx' => array('foreign_id', 'service'),
                'foreign_link_service_idx' => array('service'),
            ),
        );
    }

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

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

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

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

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

    // Make sure we only ever delete one record at a time
    public 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
// This file is part of GNU social - https://www.gnu.org/software/social
//
// GNU social is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// GNU social is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with GNU social.  If not, see <http://www.gnu.org/licenses/>.

/**
 * Table Definition for foreign_service
 */

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

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()
    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', '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
// This file is part of GNU social - https://www.gnu.org/software/social
//
// GNU social is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// GNU social is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with GNU social.  If not, see <http://www.gnu.org/licenses/>.

/**
 * Table Definition for foreign_subscription
 */

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

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()

    /* 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', '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_service_fkey' => array('foreign_user', array('subscriber' => 'id', 'service' => 'service')),
                'foreign_subscription_subscribed_service_fkey' => array('foreign_user', array('subscribed' => 'id', 'service' => 'service')),
            ),
            'indexes' => array(
                'foreign_subscription_subscriber_service_idx' => array('subscriber', 'service'),
                'foreign_subscription_subscribed_service_idx' => array('subscribed', 'service'),
                'foreign_subscription_service_subscribed_idx' => array('service', 'subscribed'),
            ),
        );
    }
}


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

/**
 * Table Definition for foreign_user
 */

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

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()
    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', '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'),
            ),
            'indexes' => array(
                'foreign_user_service_idx' => array('service'),
            ),
        );
    }

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

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