We are no longer offering accounts on this server. Consider https://gitlab.freedesktop.org/ as a place to host projects.

mediafile.php 15.3 KB
Newer Older
1 2
<?php
/**
Zach Copley's avatar
Zach Copley committed
3
 * StatusNet, the distributed open-source microblogging tool
4
 *
Zach Copley's avatar
Zach Copley committed
5 6 7
 * Abstraction for media files in general
 *
 * TODO: combine with ImageFile?
8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
 *
 * PHP version 5
 *
 * LICENCE: This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 * @category  Media
 * @package   StatusNet
Zach Copley's avatar
Zach Copley committed
26
 * @author    Robin Millette <robin@millette.info>
27 28 29 30 31 32 33 34 35 36
 * @author    Zach Copley <zach@status.net>
 * @copyright 2008-2009 StatusNet, Inc.
 * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
 * @link      http://status.net/
 */

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

37
class MediaFile
38
{
39

40 41 42 43 44 45 46 47 48 49 50
    var $filename      = null;
    var $fileRecord    = null;
    var $user          = null;
    var $fileurl       = null;
    var $short_fileurl = null;
    var $mimetype      = null;

    function __construct($user = null, $filename = null, $mimetype = null)
    {
        if ($user == null) {
            $this->user = common_current_user();
51 52
        } else {
            $this->user = $user;
53
        }
54

55 56
        $this->filename   = $filename;
        $this->mimetype   = $mimetype;
57
        $this->fileRecord = $this->storeFile();
58
        $this->thumbnailRecord = $this->storeThumbnail();
59

60 61 62 63 64 65 66
        $this->fileurl = common_local_url('attachment',
                                    array('attachment' => $this->fileRecord->id));

        $this->maybeAddRedir($this->fileRecord->id, $this->fileurl);
        $this->short_fileurl = common_shorten_url($this->fileurl);
        $this->maybeAddRedir($this->fileRecord->id, $this->short_fileurl);
    }
67

68 69 70 71
    function attachToNotice($notice)
    {
        File_to_post::processNew($this->fileRecord->id, $notice->id);
        $this->maybeAddRedir($this->fileRecord->id,
72
                             common_local_url('file', array('notice' => $notice->id)));
73
    }
74 75

    function shortUrl()
76 77 78 79 80 81 82 83 84 85 86 87 88 89
    {
        return $this->short_fileurl;
    }

    function delete()
    {
        $filepath = File::path($this->filename);
        @unlink($filepath);
    }

    function storeFile() {

        $file = new File;

90 91 92 93 94
        $file->filename = $this->filename;
        $file->url      = File::url($this->filename);
        $filepath       = File::path($this->filename);
        $file->size     = filesize($filepath);
        $file->date     = time();
95 96 97 98 99 100
        $file->mimetype = $this->mimetype;

        $file_id = $file->insert();

        if (!$file_id) {
            common_log_db_error($file, "INSERT", __FILE__);
101
            // TRANS: Client exception thrown when a database error was thrown during a file upload operation.
102 103
            throw new ClientException(_('There was a database error while saving your file. Please try again.'));
        }
104

105 106 107
        return $file;
    }

108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129
    /**
     * Generate and store a thumbnail image for the uploaded file, if applicable.
     *
     * @return File_thumbnail or null
     */
    function storeThumbnail()
    {
        if (substr($this->mimetype, 0, strlen('image/')) != 'image/') {
            // @fixme video thumbs would be nice!
            return null;
        }
        try {
            $image = new ImageFile($this->fileRecord->id,
                                   File::path($this->filename));
        } catch (Exception $e) {
            // Unsupported image type.
            return null;
        }

        $outname = File::filename($this->user->getProfile(), 'thumb-' . $this->filename, $this->mimetype);
        $outpath = File::path($outname);

130 131 132
        $maxWidth = common_config('attachments', 'thumb_width');
        $maxHeight = common_config('attachments', 'thumb_height');
        list($width, $height) = $this->scaleToFit($image->width, $image->height, $maxWidth, $maxHeight);
133 134 135 136 137 138 139 140

        $image->resizeTo($outpath, $width, $height);
        File_thumbnail::saveThumbnail($this->fileRecord->id,
                                      File::url($outname),
                                      $width,
                                      $height);
    }

141 142 143 144 145 146 147 148 149 150 151 152 153
    function scaleToFit($width, $height, $maxWidth, $maxHeight)
    {
        $aspect = $maxWidth / $maxHeight;
        $w1 = $maxWidth;
        $h1 = intval($height * $maxWidth / $width);
        if ($h1 > $maxHeight) {
            $w2 = intval($width * $maxHeight / $height);
            $h2 = $maxHeight;
            return array($w2, $h2);
        }
        return array($w1, $h1);
    }

154 155 156 157 158 159 160 161 162 163
    function rememberFile($file, $short)
    {
        $this->maybeAddRedir($file->id, $short);
    }

    function maybeAddRedir($file_id, $url)
    {
        $file_redir = File_redirection::staticGet('url', $url);

        if (empty($file_redir)) {
164

165 166 167 168 169 170 171 172
            $file_redir = new File_redirection;
            $file_redir->url = $url;
            $file_redir->file_id = $file_id;

            $result = $file_redir->insert();

            if (!$result) {
                common_log_db_error($file_redir, "INSERT", __FILE__);
173
                // TRANS: Client exception thrown when a database error was thrown during a file upload operation.
174 175 176 177 178
                throw new ClientException(_('There was a database error while saving your file. Please try again.'));
            }
        }
    }

179
    static function fromUpload($param = 'media', $user = null)
180
    {
181 182 183 184
        if (empty($user)) {
            $user = common_current_user();
        }

185 186 187
        if (!isset($_FILES[$param]['error'])){
            return;
        }
188

189 190 191 192
        switch ($_FILES[$param]['error']) {
        case UPLOAD_ERR_OK: // success, jump out
            break;
        case UPLOAD_ERR_INI_SIZE:
193
            // TRANS: Client exception thrown when an uploaded file is larger than set in php.ini.
194 195 196 197 198
            throw new ClientException(_('The uploaded file exceeds the ' .
                'upload_max_filesize directive in php.ini.'));
            return;
        case UPLOAD_ERR_FORM_SIZE:
            throw new ClientException(
199
                // TRANS: Client exception.
200 201 202 203 204
                _('The uploaded file exceeds the MAX_FILE_SIZE directive' .
                ' that was specified in the HTML form.'));
            return;
        case UPLOAD_ERR_PARTIAL:
            @unlink($_FILES[$param]['tmp_name']);
205
            // TRANS: Client exception.
206 207
            throw new ClientException(_('The uploaded file was only' .
                ' partially uploaded.'));
208
            return;
209 210 211
        case UPLOAD_ERR_NO_FILE:
            // No file; probably just a non-AJAX submission.
            return;
212
        case UPLOAD_ERR_NO_TMP_DIR:
213
            // TRANS: Client exception thrown when a temporary folder is not present to store a file upload.
214 215 216
            throw new ClientException(_('Missing a temporary folder.'));
            return;
        case UPLOAD_ERR_CANT_WRITE:
217
            // TRANS: Client exception thrown when writing to disk is not possible during a file upload operation.
218 219 220
            throw new ClientException(_('Failed to write file to disk.'));
            return;
        case UPLOAD_ERR_EXTENSION:
221
            // TRANS: Client exception thrown when a file upload operation has been stopped by an extension.
222 223 224
            throw new ClientException(_('File upload stopped by extension.'));
            return;
        default:
225 226
            common_log(LOG_ERR, __METHOD__ . ": Unknown upload error " .
                $_FILES[$param]['error']);
227
            // TRANS: Client exception thrown when a file upload operation has failed with an unknown reason.
228 229 230
            throw new ClientException(_('System error uploading file.'));
            return;
        }
231

232
        if (!MediaFile::respectsQuota($user, $_FILES[$param]['size'])) {
233

234
            // Should never actually get here
235

236
            @unlink($_FILES[$param]['tmp_name']);
237
            // TRANS: Client exception thrown when a file upload operation would cause a user to exceed a set quota.
238
            throw new ClientException(_('File exceeds user\'s quota.'));
239 240 241
            return;
        }

242 243
        $mimetype = MediaFile::getUploadedFileType($_FILES[$param]['tmp_name'],
                                                   $_FILES[$param]['name']);
244

245
        $filename = null;
246

247
        if (isset($mimetype)) {
248

249 250 251 252 253
            $basename = basename($_FILES[$param]['name']);
            $filename = File::filename($user->getProfile(), $basename, $mimetype);
            $filepath = File::path($filename);

            $result = move_uploaded_file($_FILES[$param]['tmp_name'], $filepath);
254 255

            if (!$result) {
256 257
                // TRANS: Client exception thrown when a file upload operation fails because the file could
                // TRANS: not be moved from the temporary folder to the permanent file location.
258 259 260
                throw new ClientException(_('File could not be moved to destination directory.'));
                return;
            }
261

262
        } else {
263 264
            // TRANS: Client exception thrown when a file upload operation has been stopped because the MIME
            // TRANS: type of the uploaded file could not be determined.
265
            throw new ClientException(_('Could not determine file\'s MIME type.'));
266 267
            return;
        }
268

269 270 271
        return new MediaFile($user, $filename, $mimetype);
    }

272
    static function fromFilehandle($fh, $user) {
273 274 275

        $stream = stream_get_meta_data($fh);

276
        if (!MediaFile::respectsQuota($user, filesize($stream['uri']))) {
277

278
            // Should never actually get here
279

280
            // TRANS: Client exception thrown when a file upload operation would cause a user to exceed a set quota.
281
            throw new ClientException(_('File exceeds user\'s quota.'));
282 283 284 285
            return;
        }

        $mimetype = MediaFile::getUploadedFileType($fh);
286

287
        $filename = null;
288

289 290 291 292 293
        if (isset($mimetype)) {

            $filename = File::filename($user->getProfile(), "email", $mimetype);

            $filepath = File::path($filename);
294

295
            $result = copy($stream['uri'], $filepath) && chmod($filepath, 0664);
296

297
            if (!$result) {
298 299
                // TRANS: Client exception thrown when a file upload operation fails because the file could
                // TRANS: not be moved from the temporary folder to the permanent file location.
300 301 302 303
                throw new ClientException(_('File could not be moved to destination directory.' .
                    $stream['uri'] . ' ' . $filepath));
            }
        } else {
304 305
            // TRANS: Client exception thrown when a file upload operation has been stopped because the MIME
            // TRANS: type of the uploaded file could not be determined.
306
            throw new ClientException(_('Could not determine file\'s MIME type.'));
307 308
            return;
        }
309

310 311 312
        return new MediaFile($user, $filename, $mimetype);
    }

313 314 315 316 317 318 319 320 321 322 323 324 325 326 327
    /**
     * Attempt to identify the content type of a given file.
     * 
     * @param mixed $f file handle resource, or filesystem path as string
     * @param string $originalFilename (optional) for extension-based detection
     * @return string
     * 
     * @fixme is this an internal or public method? It's called from GetFileAction
     * @fixme this seems to tie a front-end error message in, kinda confusing
     * @fixme this looks like it could return a PEAR_Error in some cases, if
     *        type can't be identified and $config['attachments']['supported'] is true
     * 
     * @throws ClientException if type is known, but not supported for local uploads
     */
    static function getUploadedFileType($f, $originalFilename=false) {
328
        require_once 'MIME/Type.php';
329
        require_once 'MIME/Type/Extension.php';
330 331 332

        // We have to disable auto handling of PEAR errors
        PEAR::staticPushErrorHandling(PEAR_ERROR_RETURN);
333
        $mte = new MIME_Type_Extension();
334

335 336
        $cmd = &PEAR::getStaticProperty('MIME_Type', 'fileCmd');
        $cmd = common_config('attachments', 'filecommand');
337

338
        $filetype = null;
339

340 341 342 343 344
        // If we couldn't get a clear type from the file extension,
        // we'll go ahead and try checking the content. Content checks
        // are unambiguous for most image files, but nearly useless
        // for office document formats.

345
        if (is_string($f)) {
346

347
            // assuming a filename
348

349
            $filetype = MIME_Type::autoDetect($f);
350

351
        } else {
352

353
            // assuming a filehandle
354

355 356 357
            $stream  = stream_get_meta_data($f);
            $filetype = MIME_Type::autoDetect($stream['uri']);
        }
358

359 360 361 362 363 364
        // The content-based sources for MIME_Type::autoDetect()
        // are wildly unreliable for office-type documents. If we've
        // gotten an unclear reponse back or just couldn't identify it,
        // we'll try detecting a type from its extension...
        $unclearTypes = array('application/octet-stream',
                              'application/vnd.ms-office',
365 366 367
                              'application/zip',
                              // TODO: for XML we could do better content-based sniffing too
                              'text/xml');
368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386

        if ($originalFilename && (!$filetype || in_array($filetype, $unclearTypes))) {
            $type = $mte->getMIMEType($originalFilename);
            if (is_string($type)) {
                $filetype = $type;
            }
        }

        $supported = common_config('attachments', 'supported');
        if (is_array($supported)) {
            // Normalize extensions to mime types
            foreach ($supported as $i => $entry) {
                if (strpos($entry, '/') === false) {
                    common_log(LOG_INFO, "sample.$entry");
                    $supported[$i] = $mte->getMIMEType("sample.$entry");
                }
            }
        }
        if ($supported === true || in_array($filetype, $supported)) {
387 388
            // Restore PEAR error handlers for our DB code...
            PEAR::staticPopErrorHandling();
389 390 391 392
            return $filetype;
        }
        $media = MIME_Type::getMedia($filetype);
        if ('application' !== $media) {
393 394 395 396 397
            // TRANS: Client exception thrown trying to upload a forbidden MIME type.
            // TRANS: %1$s is the file type that was denied, %2$s is the application part of
            // TRANS: the MIME type that was denied.
            $hint = sprintf(_('"%1$s" is not a supported file type on this server. ' .
            'Try using another %2$s format.'), $filetype, $media);
398
        } else {
399 400 401
            // TRANS: Client exception thrown trying to upload a forbidden MIME type.
            // TRANS: %s is the file type that was denied.
            $hint = sprintf(_('"%s" is not a supported file type on this server.'), $filetype);
402
        }
403 404
        // Restore PEAR error handlers for our DB code...
        PEAR::staticPopErrorHandling();
405
        throw new ClientException($hint);
406 407
    }

408
    static function respectsQuota($user, $filesize)
409 410 411 412 413 414 415 416 417 418
    {
        $file = new File;
        $result = $file->isRespectsQuota($user, $filesize);
        if ($result === true) {
            return true;
        } else {
            throw new ClientException($result);
        }
    }

419
}