File.php 27 KB

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