File.php 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685
  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; // varchar(191) not 255 because utf8mb4 takes more space
  33. public $date; // int(4)
  34. public $protected; // int(4)
  35. public $filename; // varchar(191) not 255 because utf8mb4 takes more space
  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' => 'varchar', 'length' => 191, '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' => 'varchar', 'length' => 191, 'description' => 'if a local file, name of the file'),
  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. function isProtected($url) {
  69. return 'http://www.facebook.com/login.php' === $url;
  70. }
  71. /**
  72. * Save a new file record.
  73. *
  74. * @param array $redir_data lookup data eg from File_redirection::where()
  75. * @param string $given_url
  76. * @return File
  77. */
  78. public static function saveNew(array $redir_data, $given_url) {
  79. // I don't know why we have to keep doing this but I'm adding this last check to avoid
  80. // uniqueness bugs.
  81. $file = File::getKV('urlhash', self::hashurl($given_url));
  82. if (!$file instanceof File) {
  83. $file = new File;
  84. $file->urlhash = self::hashurl($given_url);
  85. $file->url = $given_url;
  86. if (!empty($redir_data['protected'])) $file->protected = $redir_data['protected'];
  87. if (!empty($redir_data['title'])) $file->title = $redir_data['title'];
  88. if (!empty($redir_data['type'])) $file->mimetype = $redir_data['type'];
  89. if (!empty($redir_data['size'])) $file->size = intval($redir_data['size']);
  90. if (isset($redir_data['time']) && $redir_data['time'] > 0) $file->date = intval($redir_data['time']);
  91. $file_id = $file->insert();
  92. }
  93. Event::handle('EndFileSaveNew', array($file, $redir_data, $given_url));
  94. assert ($file instanceof File);
  95. return $file;
  96. }
  97. /**
  98. * Go look at a URL and possibly save data about it if it's new:
  99. * - follow redirect chains and store them in file_redirection
  100. * - if a thumbnail is available, save it in file_thumbnail
  101. * - save file record with basic info
  102. * - optionally save a file_to_post record
  103. * - return the File object with the full reference
  104. *
  105. * @fixme refactor this mess, it's gotten pretty scary.
  106. * @param string $given_url the URL we're looking at
  107. * @param int $notice_id (optional)
  108. * @param bool $followRedirects defaults to true
  109. *
  110. * @return mixed File on success, -1 on some errors
  111. *
  112. * @throws ServerException on failure
  113. */
  114. public static function processNew($given_url, $notice_id=null, $followRedirects=true) {
  115. if (empty($given_url)) {
  116. throw new ServerException('No given URL to process');
  117. }
  118. $given_url = File_redirection::_canonUrl($given_url);
  119. if (empty($given_url)) {
  120. throw new ServerException('No canonical URL from given URL to process');
  121. }
  122. $file = null;
  123. try {
  124. $file = File::getByUrl($given_url);
  125. } catch (NoResultException $e) {
  126. // First check if we have a lookup trace for this URL already
  127. try {
  128. $file_redir = File_redirection::getByUrl($given_url);
  129. $file = File::getKV('id', $file_redir->file_id);
  130. if (!$file instanceof File) {
  131. // File did not exist, let's clean up the File_redirection entry
  132. $file_redir->delete();
  133. }
  134. } catch (NoResultException $e) {
  135. // We just wanted to doublecheck whether a File_thumbnail we might've had
  136. // actually referenced an existing File object.
  137. }
  138. }
  139. // If we still don't have a File object, let's create one now!
  140. if (!$file instanceof File) {
  141. // @fixme for new URLs this also looks up non-redirect data
  142. // such as target content type, size, etc, which we need
  143. // for File::saveNew(); so we call it even if not following
  144. // new redirects.
  145. $redir_data = File_redirection::where($given_url);
  146. if (is_array($redir_data)) {
  147. $redir_url = $redir_data['url'];
  148. } elseif (is_string($redir_data)) {
  149. $redir_url = $redir_data;
  150. $redir_data = array();
  151. } else {
  152. // TRANS: Server exception thrown when a URL cannot be processed.
  153. throw new ServerException(sprintf(_("Cannot process URL '%s'"), $given_url));
  154. }
  155. if ($redir_url === $given_url || !$followRedirects) {
  156. // Save the File object based on our lookup trace
  157. $file = File::saveNew($redir_data, $given_url);
  158. } else {
  159. // This seems kind of messed up... for now skipping this part
  160. // if we're already under a redirect, so we don't go into
  161. // horrible infinite loops if we've been given an unstable
  162. // redirect (where the final destination of the first request
  163. // doesn't match what we get when we ask for it again).
  164. //
  165. // Seen in the wild with clojure.org, which redirects through
  166. // wikispaces for auth and appends session data in the URL params.
  167. $file = self::processNew($redir_url, $notice_id, /*followRedirects*/false);
  168. File_redirection::saveNew($redir_data, $file->id, $given_url);
  169. }
  170. if (!$file instanceof File) {
  171. // This should only happen if File::saveNew somehow did not return a File object,
  172. // though we have an assert for that in case the event there might've gone wrong.
  173. // If anything else goes wrong, there should've been an exception thrown.
  174. throw new ServerException('URL processing failed without new File object');
  175. }
  176. }
  177. if (!empty($notice_id)) {
  178. File_to_post::processNew($file->id, $notice_id);
  179. }
  180. return $file;
  181. }
  182. public static function respectsQuota(Profile $scoped, $fileSize) {
  183. if ($fileSize > common_config('attachments', 'file_quota')) {
  184. // TRANS: Message used to be inserted as %2$s in the text "No file may
  185. // TRANS: be larger than %1$d byte and the file you sent was %2$s.".
  186. // TRANS: %1$d is the number of bytes of an uploaded file.
  187. $fileSizeText = sprintf(_m('%1$d byte','%1$d bytes',$fileSize),$fileSize);
  188. $fileQuota = common_config('attachments', 'file_quota');
  189. // TRANS: Message given if an upload is larger than the configured maximum.
  190. // TRANS: %1$d (used for plural) is the byte limit for uploads,
  191. // TRANS: %2$s is the proper form of "n bytes". This is the only ways to have
  192. // TRANS: gettext support multiple plurals in the same message, unfortunately...
  193. throw new ClientException(
  194. 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.',
  195. 'No file may be larger than %1$d bytes and the file you sent was %2$s. Try to upload a smaller version.',
  196. $fileQuota),
  197. $fileQuota, $fileSizeText));
  198. }
  199. $file = new File;
  200. $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'";
  201. $file->query($query);
  202. $file->fetch();
  203. $total = $file->total + $fileSize;
  204. if ($total > common_config('attachments', 'user_quota')) {
  205. // TRANS: Message given if an upload would exceed user quota.
  206. // TRANS: %d (number) is the user quota in bytes and is used for plural.
  207. throw new ClientException(
  208. sprintf(_m('A file this large would exceed your user quota of %d byte.',
  209. 'A file this large would exceed your user quota of %d bytes.',
  210. common_config('attachments', 'user_quota')),
  211. common_config('attachments', 'user_quota')));
  212. }
  213. $query .= ' AND EXTRACT(month FROM file.modified) = EXTRACT(month FROM now()) and EXTRACT(year FROM file.modified) = EXTRACT(year FROM now())';
  214. $file->query($query);
  215. $file->fetch();
  216. $total = $file->total + $fileSize;
  217. if ($total > common_config('attachments', 'monthly_quota')) {
  218. // TRANS: Message given id an upload would exceed a user's monthly quota.
  219. // TRANS: $d (number) is the monthly user quota in bytes and is used for plural.
  220. throw new ClientException(
  221. sprintf(_m('A file this large would exceed your monthly quota of %d byte.',
  222. 'A file this large would exceed your monthly quota of %d bytes.',
  223. common_config('attachments', 'monthly_quota')),
  224. common_config('attachments', 'monthly_quota')));
  225. }
  226. return true;
  227. }
  228. public function getFilename()
  229. {
  230. if (!self::validFilename($this->filename)) {
  231. // TRANS: Client exception thrown if a file upload does not have a valid name.
  232. throw new ClientException(_("Invalid filename."));
  233. }
  234. return $this->filename;
  235. }
  236. // where should the file go?
  237. static function filename(Profile $profile, $origname, $mimetype)
  238. {
  239. $ext = self::guessMimeExtension($mimetype);
  240. // Normalize and make the original filename more URL friendly.
  241. $origname = basename($origname, ".$ext");
  242. if (class_exists('Normalizer')) {
  243. // http://php.net/manual/en/class.normalizer.php
  244. // http://www.unicode.org/reports/tr15/
  245. $origname = Normalizer::normalize($origname, Normalizer::FORM_KC);
  246. }
  247. $origname = preg_replace('/[^A-Za-z0-9\.\_]/', '_', $origname);
  248. $nickname = $profile->getNickname();
  249. $datestamp = strftime('%Y%m%d', time());
  250. do {
  251. // generate new random strings until we don't run into a filename collision.
  252. $random = strtolower(common_confirmation_code(16));
  253. $filename = "$nickname-$datestamp-$origname-$random.$ext";
  254. } while (file_exists(self::path($filename)));
  255. return $filename;
  256. }
  257. static function guessMimeExtension($mimetype)
  258. {
  259. try {
  260. $ext = common_supported_mime_to_ext($mimetype);
  261. } catch (Exception $e) {
  262. // We don't support this mimetype, but let's guess the extension
  263. $ext = substr(strrchr($mimetype, '/'), 1);
  264. }
  265. return strtolower($ext);
  266. }
  267. /**
  268. * Validation for as-saved base filenames
  269. */
  270. static function validFilename($filename)
  271. {
  272. return preg_match('/^[A-Za-z0-9._-]+$/', $filename);
  273. }
  274. /**
  275. * @throws ClientException on invalid filename
  276. */
  277. static function path($filename)
  278. {
  279. if (!self::validFilename($filename)) {
  280. // TRANS: Client exception thrown if a file upload does not have a valid name.
  281. throw new ClientException(_("Invalid filename."));
  282. }
  283. $dir = common_config('attachments', 'dir');
  284. if ($dir[strlen($dir)-1] != '/') {
  285. $dir .= '/';
  286. }
  287. return $dir . $filename;
  288. }
  289. static function url($filename)
  290. {
  291. if (!self::validFilename($filename)) {
  292. // TRANS: Client exception thrown if a file upload does not have a valid name.
  293. throw new ClientException(_("Invalid filename."));
  294. }
  295. if (common_config('site','private')) {
  296. return common_local_url('getfile',
  297. array('filename' => $filename));
  298. }
  299. if (GNUsocial::useHTTPS()) {
  300. $sslserver = common_config('attachments', 'sslserver');
  301. if (empty($sslserver)) {
  302. // XXX: this assumes that background dir == site dir + /file/
  303. // not true if there's another server
  304. if (is_string(common_config('site', 'sslserver')) &&
  305. mb_strlen(common_config('site', 'sslserver')) > 0) {
  306. $server = common_config('site', 'sslserver');
  307. } else if (common_config('site', 'server')) {
  308. $server = common_config('site', 'server');
  309. }
  310. $path = common_config('site', 'path') . '/file/';
  311. } else {
  312. $server = $sslserver;
  313. $path = common_config('attachments', 'sslpath');
  314. if (empty($path)) {
  315. $path = common_config('attachments', 'path');
  316. }
  317. }
  318. $protocol = 'https';
  319. } else {
  320. $path = common_config('attachments', 'path');
  321. $server = common_config('attachments', 'server');
  322. if (empty($server)) {
  323. $server = common_config('site', 'server');
  324. }
  325. $ssl = common_config('attachments', 'ssl');
  326. $protocol = ($ssl) ? 'https' : 'http';
  327. }
  328. if ($path[strlen($path)-1] != '/') {
  329. $path .= '/';
  330. }
  331. if ($path[0] != '/') {
  332. $path = '/'.$path;
  333. }
  334. return $protocol.'://'.$server.$path.$filename;
  335. }
  336. function getEnclosure(){
  337. $enclosure = (object) array();
  338. foreach (array('title', 'url', 'date', 'modified', 'size', 'mimetype') as $key) {
  339. $enclosure->$key = $this->$key;
  340. }
  341. $needMoreMetadataMimetypes = array(null, 'application/xhtml+xml');
  342. if (!isset($this->filename) && in_array(common_bare_mime($enclosure->mimetype), $needMoreMetadataMimetypes)) {
  343. // This fetches enclosure metadata for non-local links with unset/HTML mimetypes,
  344. // which may be enriched through oEmbed or similar (implemented as plugins)
  345. Event::handle('FileEnclosureMetadata', array($this, &$enclosure));
  346. }
  347. if (empty($enclosure->mimetype) || in_array(common_bare_mime($enclosure->mimetype), $needMoreMetadataMimetypes)) {
  348. // This means we either don't know what it is, so it can't
  349. // be shown as an enclosure, or it is an HTML link which
  350. // does not link to a resource with further metadata.
  351. throw new ServerException('Unknown enclosure mimetype, not enough metadata');
  352. }
  353. return $enclosure;
  354. }
  355. /**
  356. * Get the attachment's thumbnail record, if any.
  357. * Make sure you supply proper 'int' typed variables (or null).
  358. *
  359. * @param $width int Max width of thumbnail in pixels. (if null, use common_config values)
  360. * @param $height int Max height of thumbnail in pixels. (if null, square-crop to $width)
  361. * @param $crop bool Crop to the max-values' aspect ratio
  362. *
  363. * @return File_thumbnail
  364. *
  365. * @throws UseFileAsThumbnailException if the file is considered an image itself and should be itself as thumbnail
  366. * @throws UnsupportedMediaException if, despite trying, we can't understand how to make a thumbnail for this format
  367. * @throws ServerException on various other errors
  368. */
  369. public function getThumbnail($width=null, $height=null, $crop=false, $force_still=true)
  370. {
  371. // Get some more information about this file through our ImageFile class
  372. $image = ImageFile::fromFileObject($this);
  373. if ($image->animated && !common_config('thumbnail', 'animated')) {
  374. // null means "always use file as thumbnail"
  375. // false means you get choice between frozen frame or original when calling getThumbnail
  376. if (is_null(common_config('thumbnail', 'animated')) || !$force_still) {
  377. throw new UseFileAsThumbnailException($this->id);
  378. }
  379. }
  380. return $image->getFileThumbnail($width, $height, $crop);
  381. }
  382. public function getPath()
  383. {
  384. $filepath = self::path($this->filename);
  385. if (!file_exists($filepath)) {
  386. throw new FileNotFoundException($filepath);
  387. }
  388. return $filepath;
  389. }
  390. public function getUrl()
  391. {
  392. if (!empty($this->filename)) {
  393. // A locally stored file, so let's generate a URL for our instance.
  394. $url = self::url($this->filename);
  395. if (self::hashurl($url) !== $this->urlhash) {
  396. // For indexing purposes, in case we do a lookup on the 'url' field.
  397. // also we're fixing possible changes from http to https, or paths
  398. $this->updateUrl($url);
  399. }
  400. return $url;
  401. }
  402. // No local filename available, return the URL we have stored
  403. return $this->url;
  404. }
  405. static public function getByUrl($url)
  406. {
  407. $file = new File();
  408. $file->urlhash = self::hashurl($url);
  409. if (!$file->find(true)) {
  410. throw new NoResultException($file);
  411. }
  412. return $file;
  413. }
  414. /**
  415. * @param string $hashstr String of (preferrably lower case) hexadecimal characters, same as result of 'hash_file(...)'
  416. */
  417. static public function getByHash($hashstr, $alg=File::FILEHASH_ALG)
  418. {
  419. $file = new File();
  420. $file->filehash = strtolower($hashstr);
  421. if (!$file->find(true)) {
  422. throw new NoResultException($file);
  423. }
  424. return $file;
  425. }
  426. public function updateUrl($url)
  427. {
  428. $file = File::getKV('urlhash', self::hashurl($url));
  429. if ($file instanceof File) {
  430. throw new ServerException('URL already exists in DB');
  431. }
  432. $sql = 'UPDATE %1$s SET urlhash=%2$s, url=%3$s WHERE urlhash=%4$s;';
  433. $result = $this->query(sprintf($sql, $this->__table,
  434. $this->_quote((string)self::hashurl($url)),
  435. $this->_quote((string)$url),
  436. $this->_quote((string)$this->urlhash)));
  437. if ($result === false) {
  438. common_log_db_error($this, 'UPDATE', __FILE__);
  439. throw new ServerException("Could not UPDATE {$this->__table}.url");
  440. }
  441. return $result;
  442. }
  443. /**
  444. * Blow the cache of notices that link to this URL
  445. *
  446. * @param boolean $last Whether to blow the "last" cache too
  447. *
  448. * @return void
  449. */
  450. function blowCache($last=false)
  451. {
  452. self::blow('file:notice-ids:%s', $this->urlhash);
  453. if ($last) {
  454. self::blow('file:notice-ids:%s;last', $this->urlhash);
  455. }
  456. self::blow('file:notice-count:%d', $this->id);
  457. }
  458. /**
  459. * Stream of notices linking to this URL
  460. *
  461. * @param integer $offset Offset to show; default is 0
  462. * @param integer $limit Limit of notices to show
  463. * @param integer $since_id Since this notice
  464. * @param integer $max_id Before this notice
  465. *
  466. * @return array ids of notices that link to this file
  467. */
  468. function stream($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $max_id=0)
  469. {
  470. $stream = new FileNoticeStream($this);
  471. return $stream->getNotices($offset, $limit, $since_id, $max_id);
  472. }
  473. function noticeCount()
  474. {
  475. $cacheKey = sprintf('file:notice-count:%d', $this->id);
  476. $count = self::cacheGet($cacheKey);
  477. if ($count === false) {
  478. $f2p = new File_to_post();
  479. $f2p->file_id = $this->id;
  480. $count = $f2p->count();
  481. self::cacheSet($cacheKey, $count);
  482. }
  483. return $count;
  484. }
  485. public function isLocal()
  486. {
  487. return !empty($this->filename);
  488. }
  489. public function delete($useWhere=false)
  490. {
  491. // Delete the file, if it exists locally
  492. if (!empty($this->filename) && file_exists(self::path($this->filename))) {
  493. $deleted = @unlink(self::path($this->filename));
  494. if (!$deleted) {
  495. common_log(LOG_ERR, sprintf('Could not unlink existing file: "%s"', self::path($this->filename)));
  496. }
  497. }
  498. // Clear out related things in the database and filesystem, such as thumbnails
  499. if (Event::handle('FileDeleteRelated', array($this))) {
  500. $thumbs = new File_thumbnail();
  501. $thumbs->file_id = $this->id;
  502. if ($thumbs->find()) {
  503. while ($thumbs->fetch()) {
  504. $thumbs->delete();
  505. }
  506. }
  507. $f2p = new File_to_post();
  508. $f2p->file_id = $this->id;
  509. if ($f2p->find()) {
  510. while ($f2p->fetch()) {
  511. $f2p->delete();
  512. }
  513. }
  514. }
  515. // And finally remove the entry from the database
  516. return parent::delete($useWhere);
  517. }
  518. public function getTitle()
  519. {
  520. $title = $this->title ?: $this->filename;
  521. return $title ?: null;
  522. }
  523. static public function hashurl($url)
  524. {
  525. if (empty($url)) {
  526. throw new Exception('No URL provided to hash algorithm.');
  527. }
  528. return hash(self::URLHASH_ALG, $url);
  529. }
  530. static public function beforeSchemaUpdate()
  531. {
  532. $table = strtolower(get_called_class());
  533. $schema = Schema::get();
  534. $schemadef = $schema->getTableDef($table);
  535. // 2015-02-19 We have to upgrade our table definitions to have the urlhash field populated
  536. if (isset($schemadef['fields']['urlhash']) && isset($schemadef['unique keys']['file_urlhash_key'])) {
  537. // We already have the urlhash field, so no need to migrate it.
  538. return;
  539. }
  540. echo "\nFound old $table table, upgrading it to contain 'urlhash' field...";
  541. $file = new File();
  542. $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)));
  543. print "\nFound {$file->N} URLs with too long entries in file table\n";
  544. while ($file->fetch()) {
  545. // We've got a URL that is too long for our future file table
  546. // so we'll cut it. We could save the original URL, but there is
  547. // no guarantee it is complete anyway since the previous max was 255 chars.
  548. $dupfile = new File();
  549. // First we find file entries that would be duplicates of this when shortened
  550. // ... and we'll just throw the dupes out the window for now! It's already so borken.
  551. $dupfile->query(sprintf('SELECT * FROM file WHERE LEFT(url, 191) = "%1$s"', $file->shortenedurl));
  552. // Leave one of the URLs in the database by using ->find(true) (fetches first entry)
  553. if ($dupfile->find(true)) {
  554. print "\nShortening url entry for $table id: {$file->id} [";
  555. $orig = clone($dupfile);
  556. $dupfile->url = $file->shortenedurl; // make sure it's only 191 chars from now on
  557. $dupfile->update($orig);
  558. print "\nDeleting duplicate entries of too long URL on $table id: {$file->id} [";
  559. // only start deleting with this fetch.
  560. while($dupfile->fetch()) {
  561. print ".";
  562. $dupfile->delete();
  563. }
  564. print "]\n";
  565. } else {
  566. print "\nWarning! URL suddenly disappeared from database: {$file->url}\n";
  567. }
  568. }
  569. echo "...and now all the non-duplicates which are longer than 191 characters...\n";
  570. $file->query('UPDATE file SET url=LEFT(url, 191) WHERE LENGTH(url)>191');
  571. echo "\n...now running hacky pre-schemaupdate change for $table:";
  572. // We have to create a urlhash that is _not_ the primary key,
  573. // transfer data and THEN run checkSchema
  574. $schemadef['fields']['urlhash'] = array (
  575. 'type' => 'varchar',
  576. 'length' => 64,
  577. 'not null' => false, // this is because when adding column, all entries will _be_ NULL!
  578. 'description' => 'sha256 of destination URL (url field)',
  579. );
  580. $schemadef['fields']['url'] = array (
  581. 'type' => 'text',
  582. 'description' => 'destination URL after following possible redirections',
  583. );
  584. unset($schemadef['unique keys']);
  585. $schema->ensureTable($table, $schemadef);
  586. echo "DONE.\n";
  587. $classname = ucfirst($table);
  588. $tablefix = new $classname;
  589. // urlhash is hash('sha256', $url) in the File table
  590. echo "Updating urlhash fields in $table table...";
  591. // Maybe very MySQL specific :(
  592. $tablefix->query(sprintf('UPDATE %1$s SET %2$s=%3$s;',
  593. $schema->quoteIdentifier($table),
  594. 'urlhash',
  595. // The line below is "result of sha256 on column `url`"
  596. 'SHA2(url, 256)'));
  597. echo "DONE.\n";
  598. echo "Resuming core schema upgrade...";
  599. }
  600. }