File.php 32 KB

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