File.php 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963
  1. <?php
  2. /**
  3. * GNU social - a federating social network
  4. *
  5. * Abstraction for files
  6. *
  7. * LICENCE: This program is free software: you can redistribute it and/or modify
  8. * it under the terms of the GNU Affero General Public License as published by
  9. * the Free Software Foundation, either version 3 of the License, or
  10. * (at your option) any later version.
  11. *
  12. * This program is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. * GNU Affero General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU Affero General Public License
  18. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  19. *
  20. * @category Files
  21. * @package GNUsocial
  22. * @author Mikael Nordfeldth <mmn@hethane.se>
  23. * @author Miguel Dantas <biodantas@gmail.com>
  24. * @copyright 2008-2009, 2019 Free Software Foundation http://fsf.org
  25. * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
  26. * @link https://www.gnu.org/software/social/
  27. */
  28. defined('GNUSOCIAL') || die();
  29. /**
  30. * Table Definition for file
  31. */
  32. class File extends Managed_DataObject
  33. {
  34. public $__table = 'file'; // table name
  35. public $id; // int(4) primary_key not_null
  36. public $urlhash; // varchar(64) unique_key
  37. public $url; // text
  38. public $filehash; // varchar(64) indexed
  39. public $mimetype; // varchar(50)
  40. public $size; // int(4)
  41. public $title; // text()
  42. public $date; // int(4)
  43. public $protected; // int(4)
  44. public $filename; // text()
  45. public $width; // int(4)
  46. public $height; // int(4)
  47. public $modified; // timestamp() not_null default_CURRENT_TIMESTAMP
  48. const URLHASH_ALG = 'sha256';
  49. const FILEHASH_ALG = 'sha256';
  50. public static function schemaDef()
  51. {
  52. return array(
  53. 'fields' => array(
  54. 'id' => array('type' => 'serial', 'not null' => true),
  55. 'urlhash' => array('type' => 'varchar', 'length' => 64, 'not null' => true, 'description' => 'sha256 of destination URL (url field)'),
  56. 'url' => array('type' => 'text', 'description' => 'destination URL after following possible redirections'),
  57. 'filehash' => array('type' => 'varchar', 'length' => 64, 'not null' => false, 'description' => 'sha256 of the file contents, only for locally stored files of course'),
  58. 'mimetype' => array('type' => 'varchar', 'length' => 50, 'description' => 'mime type of resource'),
  59. 'size' => array('type' => 'int', 'description' => 'size of resource when available'),
  60. 'title' => array('type' => 'text', 'description' => 'title of resource when available'),
  61. 'date' => array('type' => 'int', 'description' => 'date of resource according to http query'),
  62. 'protected' => array('type' => 'int', 'description' => 'true when URL is private (needs login)'),
  63. 'filename' => array('type' => 'text', 'description' => 'if file is stored locally (too) this is the filename'),
  64. 'width' => array('type' => 'int', 'description' => 'width in pixels, if it can be described as such and data is available'),
  65. 'height' => array('type' => 'int', 'description' => 'height in pixels, if it can be described as such and data is available'),
  66. 'modified' => array('type' => 'timestamp', 'not null' => true, 'description' => 'date this record was modified'),
  67. ),
  68. 'primary key' => array('id'),
  69. 'unique keys' => array(
  70. 'file_urlhash_key' => array('urlhash'),
  71. ),
  72. 'indexes' => array(
  73. 'file_filehash_idx' => array('filehash'),
  74. ),
  75. );
  76. }
  77. public static function isProtected($url)
  78. {
  79. $protected_urls_exps = array(
  80. 'https://www.facebook.com/login.php',
  81. common_path('main/login')
  82. );
  83. foreach ($protected_urls_exps as $protected_url_exp) {
  84. if (preg_match('!^'.preg_quote($protected_url_exp).'(.*)$!i', $url) === 1) {
  85. return true;
  86. }
  87. }
  88. return false;
  89. }
  90. /**
  91. * Save a new file record.
  92. *
  93. * @param array $redir_data lookup data eg from File_redirection::where()
  94. * @param string $given_url
  95. * @return File
  96. * @throws ServerException
  97. */
  98. public static function saveNew(array $redir_data, $given_url)
  99. {
  100. $file = null;
  101. try {
  102. // I don't know why we have to keep doing this but we run a last check to avoid
  103. // uniqueness bugs.
  104. $file = File::getByUrl($given_url);
  105. return $file;
  106. } catch (NoResultException $e) {
  107. // We don't have the file's URL since before, so let's continue.
  108. }
  109. // if the given url is an local attachment url and the id already exists, don't
  110. // save a new file record. This should never happen, but let's make it foolproof
  111. // FIXME: how about attachments servers?
  112. $u = parse_url($given_url);
  113. if (isset($u['host']) && $u['host'] === common_config('site', 'server')) {
  114. $r = Router::get();
  115. // Skip the / in the beginning or $r->map won't match
  116. try {
  117. $args = $r->map(mb_substr($u['path'], 1));
  118. if ($args['action'] === 'attachment') {
  119. try {
  120. if (!empty($args['attachment'])) {
  121. return File::getByID($args['attachment']);
  122. } elseif ($args['filehash']) {
  123. return File::getByHash($args['filehash']);
  124. }
  125. } catch (NoResultException $e) {
  126. // apparently this link goes to us, but is _not_ an existing attachment (File) ID?
  127. }
  128. }
  129. } catch (Exception $e) {
  130. // Some other exception was thrown from $r->map, likely a
  131. // ClientException (404) because of some malformed link to
  132. // our own instance. It's still a valid URL however, so we
  133. // won't abort anything... I noticed this when linking:
  134. // https://social.umeahackerspace.se/mmn/foaf' (notice the
  135. // apostrophe in the end, making it unrecognizable for our
  136. // URL routing.
  137. // That specific issue (the apostrophe being part of a link
  138. // is something that may or may not have been fixed since,
  139. // in lib/util.php in common_replace_urls_callback().
  140. }
  141. }
  142. $file = new File;
  143. $file->url = $given_url;
  144. if (!empty($redir_data['protected'])) {
  145. $file->protected = $redir_data['protected'];
  146. }
  147. if (!empty($redir_data['title'])) {
  148. $file->title = $redir_data['title'];
  149. }
  150. if (!empty($redir_data['type'])) {
  151. $file->mimetype = $redir_data['type'];
  152. }
  153. if (!empty($redir_data['size'])) {
  154. $file->size = intval($redir_data['size']);
  155. }
  156. if (isset($redir_data['time']) && $redir_data['time'] > 0) {
  157. $file->date = intval($redir_data['time']);
  158. }
  159. $file->saveFile();
  160. return $file;
  161. }
  162. public function saveFile()
  163. {
  164. $this->urlhash = self::hashurl($this->url);
  165. if (!Event::handle('StartFileSaveNew', array(&$this))) {
  166. throw new ServerException('File not saved due to an aborted StartFileSaveNew event.');
  167. }
  168. $this->id = $this->insert();
  169. if ($this->id === false) {
  170. throw new ServerException('File/URL metadata could not be saved to the database.');
  171. }
  172. Event::handle('EndFileSaveNew', array($this));
  173. }
  174. /**
  175. * Go look at a URL and possibly save data about it if it's new:
  176. * - follow redirect chains and store them in file_redirection
  177. * - if a thumbnail is available, save it in file_thumbnail
  178. * - save file record with basic info
  179. * - optionally save a file_to_post record
  180. * - return the File object with the full reference
  181. *
  182. * @param string $given_url the URL we're looking at
  183. * @param Notice $notice (optional)
  184. * @param bool $followRedirects defaults to true
  185. *
  186. * @return mixed File on success, -1 on some errors
  187. *
  188. * @throws ServerException on failure
  189. */
  190. public static function processNew($given_url, Notice $notice=null, $followRedirects=true)
  191. {
  192. if (empty($given_url)) {
  193. throw new ServerException('No given URL to process');
  194. }
  195. $given_url = File_redirection::_canonUrl($given_url);
  196. if (empty($given_url)) {
  197. throw new ServerException('No canonical URL from given URL to process');
  198. }
  199. $redir = File_redirection::where($given_url);
  200. try {
  201. $file = $redir->getFile();
  202. } catch (EmptyPkeyValueException $e) {
  203. common_log(LOG_ERR, 'File_redirection::where gave object with empty file_id for given_url '._ve($given_url));
  204. throw new ServerException('URL processing failed without new File object');
  205. } catch (NoResultException $e) {
  206. // This should not happen
  207. common_log(LOG_ERR, 'File_redirection after discovery could still not return a File object.');
  208. throw new ServerException('URL processing failed without new File object');
  209. }
  210. if ($notice instanceof Notice) {
  211. File_to_post::processNew($file, $notice);
  212. }
  213. return $file;
  214. }
  215. public static function respectsQuota(Profile $scoped, $fileSize)
  216. {
  217. if ($fileSize > common_config('attachments', 'file_quota')) {
  218. // TRANS: Message used to be inserted as %2$s in the text "No file may
  219. // TRANS: be larger than %1$d byte and the file you sent was %2$s.".
  220. // TRANS: %1$d is the number of bytes of an uploaded file.
  221. $fileSizeText = sprintf(_m('%1$d byte', '%1$d bytes', $fileSize), $fileSize);
  222. $fileQuota = common_config('attachments', 'file_quota');
  223. // TRANS: Message given if an upload is larger than the configured maximum.
  224. // TRANS: %1$d (used for plural) is the byte limit for uploads,
  225. // TRANS: %2$s is the proper form of "n bytes". This is the only ways to have
  226. // TRANS: gettext support multiple plurals in the same message, unfortunately...
  227. throw new ClientException(
  228. sprintf(
  229. _m(
  230. 'No file may be larger than %1$d byte and the file you sent was %2$s. Try to upload a smaller version.',
  231. 'No file may be larger than %1$d bytes and the file you sent was %2$s. Try to upload a smaller version.',
  232. $fileQuota
  233. ),
  234. $fileQuota,
  235. $fileSizeText
  236. )
  237. );
  238. }
  239. $file = new File;
  240. $query = "select sum(size) as total from file join file_to_post on file_to_post.file_id = file.id join notice on file_to_post.post_id = notice.id where profile_id = {$scoped->id} and file.url like '%/notice/%/file'";
  241. $file->query($query);
  242. $file->fetch();
  243. $total = $file->total + $fileSize;
  244. if ($total > common_config('attachments', 'user_quota')) {
  245. // TRANS: Message given if an upload would exceed user quota.
  246. // TRANS: %d (number) is the user quota in bytes and is used for plural.
  247. throw new ClientException(
  248. sprintf(
  249. _m(
  250. 'A file this large would exceed your user quota of %d byte.',
  251. 'A file this large would exceed your user quota of %d bytes.',
  252. common_config('attachments', 'user_quota')
  253. ),
  254. common_config('attachments', 'user_quota')
  255. )
  256. );
  257. }
  258. $query .= ' AND EXTRACT(month FROM file.modified) = EXTRACT(month FROM now()) and EXTRACT(year FROM file.modified) = EXTRACT(year FROM now())';
  259. $file->query($query);
  260. $file->fetch();
  261. $total = $file->total + $fileSize;
  262. if ($total > common_config('attachments', 'monthly_quota')) {
  263. // TRANS: Message given id an upload would exceed a user's monthly quota.
  264. // TRANS: $d (number) is the monthly user quota in bytes and is used for plural.
  265. throw new ClientException(
  266. sprintf(
  267. _m(
  268. 'A file this large would exceed your monthly quota of %d byte.',
  269. 'A file this large would exceed your monthly quota of %d bytes.',
  270. common_config('attachments', 'monthly_quota')
  271. ),
  272. common_config('attachments', 'monthly_quota')
  273. )
  274. );
  275. }
  276. return true;
  277. }
  278. public function getFilename()
  279. {
  280. return self::tryFilename($this->filename);
  281. }
  282. public function getSize()
  283. {
  284. return intval($this->size);
  285. }
  286. // where should the file go?
  287. public static function filename(Profile $profile, $origname, $mimetype)
  288. {
  289. $ext = self::guessMimeExtension($mimetype, $origname);
  290. // Normalize and make the original filename more URL friendly.
  291. $origname = basename($origname, ".$ext");
  292. if (class_exists('Normalizer')) {
  293. // http://php.net/manual/en/class.normalizer.php
  294. // http://www.unicode.org/reports/tr15/
  295. $origname = Normalizer::normalize($origname, Normalizer::FORM_KC);
  296. }
  297. $origname = preg_replace('/[^A-Za-z0-9\.\_]/', '_', $origname);
  298. $nickname = $profile->getNickname();
  299. $datestamp = strftime('%Y%m%d', time());
  300. do {
  301. // generate new random strings until we don't run into a filename collision.
  302. $random = strtolower(common_confirmation_code(16));
  303. $filename = "$nickname-$datestamp-$origname-$random.$ext";
  304. } while (file_exists(self::path($filename)));
  305. return $filename;
  306. }
  307. /**
  308. * @param string $filename
  309. * @return string|bool Value from the 'extblacklist' array, in the config
  310. */
  311. public static function getSafeExtension(string $filename) {
  312. if (preg_match('/^.+?\.([A-Za-z0-9]+)$/', $filename, $matches) === 1) {
  313. // we matched on a file extension, so let's see if it means something.
  314. $ext = mb_strtolower($matches[1]);
  315. $blacklist = common_config('attachments', 'extblacklist');
  316. // If we got an extension from $filename we want to check if it's in a blacklist
  317. // so we avoid people uploading restricted files
  318. if (array_key_exists($ext, $blacklist)) {
  319. if (!is_string($blacklist[$ext])) {
  320. // Blocked
  321. return false;
  322. }
  323. // return a safe replacement extension ('php' => 'phps' for example)
  324. return $blacklist[$ext];
  325. } else {
  326. // the attachment extension based on its filename was not blacklisted so it's ok to use it
  327. return $ext;
  328. }
  329. } else {
  330. // No extension
  331. return null;
  332. }
  333. }
  334. /**
  335. * @param $mimetype string The mimetype we've discovered for this file.
  336. * @param $filename string An optional filename which we can use on failure.
  337. * @return mixed|string
  338. * @throws ClientException
  339. */
  340. public static function guessMimeExtension($mimetype, $filename=null)
  341. {
  342. try {
  343. // first see if we know the extension for our mimetype
  344. $ext = common_supported_mime_to_ext($mimetype);
  345. // we do, so use it!
  346. return $ext;
  347. } catch (UnknownMimeExtensionException $e) {
  348. // We don't know the extension for this mimetype, but let's guess.
  349. // If we can't recognize the extension from the MIME, we try
  350. // to guess based on filename, if one was supplied.
  351. if (!is_null($filename)) {
  352. $ext = getSafeExtension($filename);
  353. if ($ext === false) {
  354. // we don't have a safe replacement extension
  355. throw new ClientException(_('Blacklisted file extension.'));
  356. } else {
  357. return $ext;
  358. }
  359. }
  360. } catch (Exception $e) {
  361. common_log(LOG_INFO, 'Problem when figuring out extension for mimetype: '._ve($e));
  362. }
  363. // If nothing else has given us a result, try to extract it from
  364. // the mimetype value (this turns .jpg to .jpeg for example...)
  365. $matches = array();
  366. // Will get jpeg from image/jpeg as well as json from application/jrd+json
  367. if (!preg_match('/[\/+-\.]([a-z0-9]+)/', mb_strtolower($mimetype), $matches)) {
  368. throw new Exception("Malformed mimetype: {$mimetype}");
  369. }
  370. return mb_strtolower($matches[1]);
  371. }
  372. /**
  373. * Validation for as-saved base filenames
  374. * @param $filename
  375. * @return false|int
  376. */
  377. public static function validFilename($filename)
  378. {
  379. return preg_match('/^[A-Za-z0-9._-]+$/', $filename);
  380. }
  381. public static function tryFilename($filename)
  382. {
  383. if (!self::validFilename($filename)) {
  384. throw new InvalidFilenameException($filename);
  385. }
  386. // if successful, return the filename for easy if-statementing
  387. return $filename;
  388. }
  389. /**
  390. * @param $filename
  391. * @return string
  392. * @throws InvalidFilenameException
  393. */
  394. public static function path($filename)
  395. {
  396. self::tryFilename($filename);
  397. $dir = common_config('attachments', 'dir');
  398. if (!in_array($dir[mb_strlen($dir)-1], ['/', '\\'])) {
  399. $dir .= DIRECTORY_SEPARATOR;
  400. }
  401. return $dir . $filename;
  402. }
  403. public static function url($filename)
  404. {
  405. self::tryFilename($filename);
  406. if (common_config('site', 'private')) {
  407. return common_local_url(
  408. 'getfile',
  409. array('filename' => $filename)
  410. );
  411. }
  412. if (GNUsocial::useHTTPS()) {
  413. $sslserver = common_config('attachments', 'sslserver');
  414. if (empty($sslserver)) {
  415. // XXX: this assumes that background dir == site dir + /file/
  416. // not true if there's another server
  417. if (is_string(common_config('site', 'sslserver')) &&
  418. mb_strlen(common_config('site', 'sslserver')) > 0) {
  419. $server = common_config('site', 'sslserver');
  420. } elseif (common_config('site', 'server')) {
  421. $server = common_config('site', 'server');
  422. }
  423. $path = common_config('site', 'path') . '/file/';
  424. } else {
  425. $server = $sslserver;
  426. $path = common_config('attachments', 'sslpath');
  427. if (empty($path)) {
  428. $path = common_config('attachments', 'path');
  429. }
  430. }
  431. $protocol = 'https';
  432. } else {
  433. $path = common_config('attachments', 'path');
  434. $server = common_config('attachments', 'server');
  435. if (empty($server)) {
  436. $server = common_config('site', 'server');
  437. }
  438. $ssl = common_config('attachments', 'ssl');
  439. $protocol = ($ssl) ? 'https' : 'http';
  440. }
  441. if ($path[strlen($path)-1] != '/') {
  442. $path .= '/';
  443. }
  444. if ($path[0] != '/') {
  445. $path = '/'.$path;
  446. }
  447. return $protocol.'://'.$server.$path.$filename;
  448. }
  449. public static $_enclosures = array();
  450. /**
  451. * Returns metadata of a file with the properties:
  452. * title
  453. * url
  454. * date
  455. * modified
  456. * size
  457. * mimetype
  458. * width
  459. * height
  460. * @return object with the given properties
  461. * @throw ServerException if no metadata is found
  462. */
  463. public function getEnclosure()
  464. {
  465. if (isset(self::$_enclosures[$this->getID()])) {
  466. return self::$_enclosures[$this->getID()];
  467. }
  468. $enclosure = (object) array();
  469. foreach (['title', 'url', 'date', 'modified', 'size', 'mimetype', 'width', 'height'] as $key) {
  470. if ($this->$key !== '') {
  471. $enclosure->$key = $this->$key;
  472. }
  473. }
  474. $needMoreMetadataMimetypes = [null, 'application/xhtml+xml', 'text/html'];
  475. if (!isset($this->filename) && in_array(common_bare_mime($enclosure->mimetype), $needMoreMetadataMimetypes)) {
  476. // This fetches enclosure metadata for non-local links with unset/HTML mimetypes,
  477. // which may be enriched through oEmbed or similar (implemented as plugins)
  478. Event::handle('FileEnclosureMetadata', [$this, &$enclosure]);
  479. }
  480. if (empty($enclosure->mimetype)) {
  481. // This means we either don't know what it is, so it can't
  482. // be shown as an enclosure, or it is an HTML link which
  483. // does not link to a resource with further metadata.
  484. throw new ServerException('Unknown enclosure mimetype, not enough metadata');
  485. }
  486. self::$_enclosures[$this->getID()] = $enclosure;
  487. return $enclosure;
  488. }
  489. public function hasThumbnail()
  490. {
  491. try {
  492. $this->getThumbnail();
  493. } catch (Exception $e) {
  494. return false;
  495. }
  496. return true;
  497. }
  498. /**
  499. * Get the attachment's thumbnail record, if any.
  500. * Make sure you supply proper 'int' typed variables (or null).
  501. *
  502. * @param $width int Max width of thumbnail in pixels. (if null, use common_config values)
  503. * @param $height int Max height of thumbnail in pixels. (if null, square-crop to $width)
  504. * @param $crop bool Crop to the max-values' aspect ratio
  505. * @param $force_still bool Don't allow fallback to showing original (such as animated GIF)
  506. * @param $upscale mixed Whether or not to scale smaller images up to larger thumbnail sizes. (null = site default)
  507. *
  508. * @return File_thumbnail
  509. *
  510. * @throws UseFileAsThumbnailException if the file is considered an image itself and should be itself as thumbnail
  511. * @throws UnsupportedMediaException if, despite trying, we can't understand how to make a thumbnail for this format
  512. * @throws ServerException on various other errors
  513. */
  514. public function getThumbnail($width=null, $height=null, $crop=false, $force_still=true, $upscale=null)
  515. {
  516. // Get some more information about this file through our ImageFile class
  517. $image = ImageFile::fromFileObject($this);
  518. if ($image->animated && !common_config('thumbnail', 'animated')) {
  519. // null means "always use file as thumbnail"
  520. // false means you get choice between frozen frame or original when calling getThumbnail
  521. if (is_null(common_config('thumbnail', 'animated')) || !$force_still) {
  522. try {
  523. // remote files with animated GIFs as thumbnails will match this
  524. return File_thumbnail::byFile($this);
  525. } catch (NoResultException $e) {
  526. // and if it's not a remote file, it'll be safe to use the locally stored File
  527. throw new UseFileAsThumbnailException($this);
  528. }
  529. }
  530. }
  531. return $image->getFileThumbnail(
  532. $width,
  533. $height,
  534. $crop,
  535. !is_null($upscale) ? $upscale : common_config('thumbnail', 'upscale')
  536. );
  537. }
  538. public function getPath()
  539. {
  540. $filepath = self::path($this->filename);
  541. if (!file_exists($filepath)) {
  542. throw new FileNotFoundException($filepath);
  543. }
  544. return $filepath;
  545. }
  546. /**
  547. * Returns the path to either a file, or it's thumbnail if the file doesn't exist.
  548. * This is useful in case the original file is deleted, or, as is the case for Embed
  549. * thumbnails, we only have a thumbnail and not a file
  550. * @return string Path
  551. * @throws FileNotFoundException
  552. * @throws FileNotStoredLocallyException
  553. * @throws InvalidFilenameException
  554. * @throws ServerException
  555. */
  556. public function getFileOrThumbnailPath($thumbnail = null) : string
  557. {
  558. if (!empty($thumbnail)) {
  559. return $thumbnail->getPath();
  560. }
  561. if (!empty($this->filename)) {
  562. $filepath = self::path($this->filename);
  563. if (file_exists($filepath)) {
  564. return $filepath;
  565. } else {
  566. throw new FileNotFoundException($filepath);
  567. }
  568. } else {
  569. try {
  570. return File_thumbnail::byFile($this, true)->getPath();
  571. } catch (NoResultException $e) {
  572. // File not stored locally
  573. throw new FileNotStoredLocallyException($this);
  574. }
  575. }
  576. }
  577. /**
  578. * Return the mime type of the thumbnail if we have it, or, if not, of the File
  579. * @return string
  580. * @throws FileNotFoundException
  581. * @throws NoResultException
  582. * @throws ServerException
  583. * @throws UnsupportedMediaException
  584. */
  585. public function getFileOrThumbnailMimetype($thumbnail = null) : string
  586. {
  587. if (!empty($thumbnail)) {
  588. $filepath = $thumbnail->getPath();
  589. } elseif (!empty($this->filename)) {
  590. return $this->mimetype;
  591. } else {
  592. $filepath = File_thumbnail::byFile($this, true)->getPath();
  593. }
  594. $info = @getimagesize($filepath);
  595. if ($info !== false) {
  596. return $info['mime'];
  597. } else {
  598. throw new UnsupportedMediaException(_("Thumbnail is not an image."));
  599. }
  600. }
  601. /**
  602. * Return the size of the thumbnail if we have it, or, if not, of the File
  603. * @return int
  604. * @throws FileNotFoundException
  605. * @throws NoResultException
  606. * @throws ServerException
  607. */
  608. public function getFileOrThumbnailSize($thumbnail = null) : int
  609. {
  610. if (!empty($thumbnail)) {
  611. return filesize($thumbnail->getPath());
  612. } elseif (!empty($this->filename)) {
  613. return $this->size;
  614. } else {
  615. return filesize(File_thumbnail::byFile($this)->getPath());
  616. }
  617. }
  618. public function getAttachmentUrl()
  619. {
  620. return common_local_url('attachment', array('attachment'=>$this->getID()));
  621. }
  622. public function getAttachmentDownloadUrl()
  623. {
  624. return common_local_url('attachment_download', array('attachment'=>$this->getID()));
  625. }
  626. public function getAttachmentViewUrl()
  627. {
  628. return common_local_url('attachment_view', array('attachment'=>$this->getID()));
  629. }
  630. /**
  631. * @param mixed $use_local true means require local, null means prefer local, false means use whatever is stored
  632. * @return string
  633. * @throws FileNotStoredLocallyException
  634. */
  635. public function getUrl($use_local=null)
  636. {
  637. if ($use_local !== false) {
  638. if (is_string($this->filename) || !empty($this->filename)) {
  639. // A locally stored file, so let's generate a URL for our instance.
  640. return $this->getAttachmentViewUrl();
  641. }
  642. if ($use_local) {
  643. // if the file wasn't stored locally (has filename) and we require a local URL
  644. throw new FileNotStoredLocallyException($this);
  645. }
  646. }
  647. // No local filename available, return the URL we have stored
  648. return $this->url;
  649. }
  650. public static function getByUrl($url)
  651. {
  652. $file = new File();
  653. $file->urlhash = self::hashurl($url);
  654. if (!$file->find(true)) {
  655. throw new NoResultException($file);
  656. }
  657. return $file;
  658. }
  659. /**
  660. * @param string $hashstr String of (preferrably lower case) hexadecimal characters, same as result of 'hash_file(...)'
  661. * @return File
  662. * @throws NoResultException
  663. */
  664. public static function getByHash($hashstr)
  665. {
  666. $file = new File();
  667. $file->filehash = strtolower($hashstr);
  668. if (!$file->find(true)) {
  669. throw new NoResultException($file);
  670. }
  671. return $file;
  672. }
  673. public function updateUrl($url)
  674. {
  675. $file = File::getKV('urlhash', self::hashurl($url));
  676. if ($file instanceof File) {
  677. throw new ServerException('URL already exists in DB');
  678. }
  679. $sql = 'UPDATE %1$s SET urlhash=%2$s, url=%3$s WHERE urlhash=%4$s;';
  680. $result = $this->query(sprintf(
  681. $sql,
  682. $this->tableName(),
  683. $this->_quote((string)self::hashurl($url)),
  684. $this->_quote((string)$url),
  685. $this->_quote((string)$this->urlhash)
  686. ));
  687. if ($result === false) {
  688. common_log_db_error($this, 'UPDATE', __FILE__);
  689. throw new ServerException("Could not UPDATE {$this->tableName()}.url");
  690. }
  691. return $result;
  692. }
  693. /**
  694. * Blow the cache of notices that link to this URL
  695. *
  696. * @param boolean $last Whether to blow the "last" cache too
  697. *
  698. * @return void
  699. */
  700. public function blowCache($last=false)
  701. {
  702. self::blow('file:notice-ids:%s', $this->id);
  703. if ($last) {
  704. self::blow('file:notice-ids:%s;last', $this->id);
  705. }
  706. self::blow('file:notice-count:%d', $this->id);
  707. }
  708. /**
  709. * Stream of notices linking to this URL
  710. *
  711. * @param integer $offset Offset to show; default is 0
  712. * @param integer $limit Limit of notices to show
  713. * @param integer $since_id Since this notice
  714. * @param integer $max_id Before this notice
  715. *
  716. * @return array ids of notices that link to this file
  717. */
  718. public function stream($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $max_id=0)
  719. {
  720. // FIXME: Try to get the Profile::current() here in some other way to avoid mixing
  721. // the current session user with possibly background/queue processing.
  722. $stream = new FileNoticeStream($this, Profile::current());
  723. return $stream->getNotices($offset, $limit, $since_id, $max_id);
  724. }
  725. public function noticeCount()
  726. {
  727. $cacheKey = sprintf('file:notice-count:%d', $this->id);
  728. $count = self::cacheGet($cacheKey);
  729. if ($count === false) {
  730. $f2p = new File_to_post();
  731. $f2p->file_id = $this->id;
  732. $count = $f2p->count();
  733. self::cacheSet($cacheKey, $count);
  734. }
  735. return $count;
  736. }
  737. public function isLocal()
  738. {
  739. return !empty($this->filename);
  740. }
  741. public function delete($useWhere=false)
  742. {
  743. // Delete the file, if it exists locally
  744. if (!empty($this->filename) && file_exists(self::path($this->filename))) {
  745. $deleted = @unlink(self::path($this->filename));
  746. if (!$deleted) {
  747. common_log(LOG_ERR, sprintf('Could not unlink existing file: "%s"', self::path($this->filename)));
  748. }
  749. }
  750. // Clear out related things in the database and filesystem, such as thumbnails
  751. if (Event::handle('FileDeleteRelated', array($this))) {
  752. $thumbs = new File_thumbnail();
  753. $thumbs->file_id = $this->id;
  754. if ($thumbs->find()) {
  755. while ($thumbs->fetch()) {
  756. $thumbs->delete();
  757. }
  758. }
  759. $f2p = new File_to_post();
  760. $f2p->file_id = $this->id;
  761. if ($f2p->find()) {
  762. while ($f2p->fetch()) {
  763. $f2p->delete();
  764. }
  765. }
  766. }
  767. // And finally remove the entry from the database
  768. return parent::delete($useWhere);
  769. }
  770. public function getTitle()
  771. {
  772. $title = $this->title ?: MediaFile::getDisplayName($this);
  773. return $title ?: null;
  774. }
  775. public function setTitle($title)
  776. {
  777. $orig = clone($this);
  778. $this->title = mb_strlen($title) > 0 ? $title : null;
  779. return $this->update($orig);
  780. }
  781. public static function hashurl($url)
  782. {
  783. if (empty($url)) {
  784. throw new Exception('No URL provided to hash algorithm.');
  785. }
  786. return hash(self::URLHASH_ALG, $url);
  787. }
  788. public static function beforeSchemaUpdate()
  789. {
  790. $table = strtolower(get_called_class());
  791. $schema = Schema::get();
  792. $schemadef = $schema->getTableDef($table);
  793. // 2015-02-19 We have to upgrade our table definitions to have the urlhash field populated
  794. if (isset($schemadef['fields']['urlhash']) && isset($schemadef['unique keys']['file_urlhash_key'])) {
  795. // We already have the urlhash field, so no need to migrate it.
  796. return;
  797. }
  798. echo "\nFound old $table table, upgrading it to contain 'urlhash' field...";
  799. $file = new File();
  800. $file->query(sprintf('SELECT id, LEFT(url, 191) AS shortenedurl, COUNT(*) AS c FROM %1$s WHERE LENGTH(url)>191 GROUP BY shortenedurl HAVING c > 1', $schema->quoteIdentifier($table)));
  801. print "\nFound {$file->N} URLs with too long entries in file table\n";
  802. while ($file->fetch()) {
  803. // We've got a URL that is too long for our future file table
  804. // so we'll cut it. We could save the original URL, but there is
  805. // no guarantee it is complete anyway since the previous max was 255 chars.
  806. $dupfile = new File();
  807. // First we find file entries that would be duplicates of this when shortened
  808. // ... and we'll just throw the dupes out the window for now! It's already so borken.
  809. $dupfile->query(sprintf('SELECT * FROM file WHERE LEFT(url, 191) = %1$s', $dupfile->_quote($file->shortenedurl)));
  810. // Leave one of the URLs in the database by using ->find(true) (fetches first entry)
  811. if ($dupfile->find(true)) {
  812. print "\nShortening url entry for $table id: {$file->id} [";
  813. $orig = clone($dupfile);
  814. $origurl = $dupfile->url; // save for logging purposes
  815. $dupfile->url = $file->shortenedurl; // make sure it's only 191 chars from now on
  816. $dupfile->update($orig);
  817. print "\nDeleting duplicate entries of too long URL on $table id: {$file->id} [";
  818. // only start deleting with this fetch.
  819. while ($dupfile->fetch()) {
  820. 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));
  821. print ".";
  822. $dupfile->delete();
  823. }
  824. print "]\n";
  825. } else {
  826. print "\nWarning! URL suddenly disappeared from database: {$file->url}\n";
  827. }
  828. }
  829. echo "...and now all the non-duplicates which are longer than 191 characters...\n";
  830. $file->query('UPDATE file SET url=LEFT(url, 191) WHERE LENGTH(url)>191');
  831. echo "\n...now running hacky pre-schemaupdate change for $table:";
  832. // We have to create a urlhash that is _not_ the primary key,
  833. // transfer data and THEN run checkSchema
  834. $schemadef['fields']['urlhash'] = array(
  835. 'type' => 'varchar',
  836. 'length' => 64,
  837. 'not null' => false, // this is because when adding column, all entries will _be_ NULL!
  838. 'description' => 'sha256 of destination URL (url field)',
  839. );
  840. $schemadef['fields']['url'] = array(
  841. 'type' => 'text',
  842. 'description' => 'destination URL after following possible redirections',
  843. );
  844. unset($schemadef['unique keys']);
  845. $schema->ensureTable($table, $schemadef);
  846. echo "DONE.\n";
  847. $classname = ucfirst($table);
  848. $tablefix = new $classname;
  849. // urlhash is hash('sha256', $url) in the File table
  850. echo "Updating urlhash fields in $table table...";
  851. // Maybe very MySQL specific :(
  852. $tablefix->query(sprintf(
  853. 'UPDATE %1$s SET %2$s=%3$s;',
  854. $schema->quoteIdentifier($table),
  855. 'urlhash',
  856. // The line below is "result of sha256 on column `url`"
  857. 'SHA2(url, 256)'
  858. ));
  859. echo "DONE.\n";
  860. echo "Resuming core schema upgrade...";
  861. }
  862. }