File_thumbnail.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311
  1. <?php
  2. // This file is part of GNU social - https://www.gnu.org/software/social
  3. //
  4. // GNU social is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Affero General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // GNU social is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU Affero General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Affero General Public License
  15. // along with GNU social. If not, see <http://www.gnu.org/licenses/>.
  16. /*
  17. * @copyright 2008-2009 StatusNet, Inc.
  18. * @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
  19. */
  20. defined('GNUSOCIAL') || die();
  21. /**
  22. * Table Definition for file_thumbnail
  23. */
  24. class File_thumbnail extends Managed_DataObject
  25. {
  26. public $__table = 'file_thumbnail'; // table name
  27. public $file_id; // int(4) primary_key not_null
  28. public $urlhash; // varchar(64) indexed
  29. public $url; // text
  30. public $filename; // text
  31. public $width; // int(4) primary_key
  32. public $height; // int(4) primary_key
  33. public $modified; // timestamp() not_null default_CURRENT_TIMESTAMP
  34. const URLHASH_ALG = 'sha256';
  35. public static function schemaDef()
  36. {
  37. return array(
  38. 'fields' => array(
  39. 'file_id' => array('type' => 'int', 'not null' => true, 'description' => 'thumbnail for what URL/file'),
  40. 'urlhash' => array('type' => 'varchar', 'length' => 64, 'description' => 'sha256 of url field if non-empty'),
  41. 'url' => array('type' => 'text', 'description' => 'URL of thumbnail'),
  42. 'filename' => array('type' => 'text', 'description' => 'if stored locally, filename is put here'),
  43. 'width' => array('type' => 'int', 'not null' => true, 'description' => 'width of thumbnail'),
  44. 'height' => array('type' => 'int', 'not null' => true, 'description' => 'height of thumbnail'),
  45. 'modified' => array('type' => 'timestamp', 'not null' => true, 'description' => 'date this record was modified'),
  46. ),
  47. 'primary key' => array('file_id', 'width', 'height'),
  48. 'indexes' => array(
  49. 'file_thumbnail_urlhash_idx' => array('urlhash'),
  50. ),
  51. 'foreign keys' => array(
  52. 'file_thumbnail_file_id_fkey' => array('file', array('file_id' => 'id')),
  53. )
  54. );
  55. }
  56. /**
  57. * Save oEmbed-provided thumbnail data
  58. *
  59. * @param object $data
  60. * @param int $file_id
  61. */
  62. public static function saveNew($data, $file_id)
  63. {
  64. if (!empty($data->thumbnail_url)) {
  65. // Non-photo types such as video will usually
  66. // show us a thumbnail, though it's not required.
  67. self::saveThumbnail(
  68. $file_id,
  69. $data->thumbnail_url,
  70. $data->thumbnail_width,
  71. $data->thumbnail_height
  72. );
  73. } elseif ($data->type == 'photo') {
  74. // The inline photo URL given should also fit within
  75. // our requested thumbnail size, per oEmbed spec.
  76. self::saveThumbnail(
  77. $file_id,
  78. $data->url,
  79. $data->width,
  80. $data->height
  81. );
  82. }
  83. }
  84. /**
  85. * Fetch an entry by using a File's id
  86. *
  87. * @param File $file The File object we're getting a thumbnail for.
  88. * @param boolean $notNullUrl Originally remote thumbnails have a URL stored, we use this to find the "original"
  89. *
  90. * @return File_thumbnail
  91. * @throws NoResultException if no File_thumbnail matched the criteria
  92. */
  93. public static function byFile(File $file, $notNullUrl = true)
  94. {
  95. $thumb = new File_thumbnail();
  96. $thumb->file_id = $file->getID();
  97. if ($notNullUrl) {
  98. $thumb->whereAdd('url IS NOT NULL');
  99. }
  100. $thumb->orderBy('modified ASC'); // the first created, a somewhat ugly hack
  101. $thumb->limit(1);
  102. if (!$thumb->find(true)) {
  103. throw new NoResultException($thumb);
  104. }
  105. return $thumb;
  106. }
  107. /**
  108. * Save a thumbnail record for the referenced file record.
  109. *
  110. * FIXME: Add error handling
  111. *
  112. * @param int $file_id
  113. * @param string $url
  114. * @param int $width
  115. * @param int $height
  116. */
  117. public static function saveThumbnail($file_id, $url, $width, $height, $filename = null)
  118. {
  119. $tn = new File_thumbnail;
  120. $tn->file_id = $file_id;
  121. $tn->url = $url;
  122. $tn->filename = $filename;
  123. $tn->width = intval($width);
  124. $tn->height = intval($height);
  125. $tn->insert();
  126. return $tn;
  127. }
  128. public static function path($filename)
  129. {
  130. File::tryFilename($filename);
  131. // NOTE: If this is left empty in default config, it will be set to File::path('thumb')
  132. $dir = common_config('thumbnail', 'dir');
  133. if (!in_array($dir[mb_strlen($dir)-1], ['/', '\\'])) {
  134. $dir .= DIRECTORY_SEPARATOR;
  135. }
  136. return $dir . $filename;
  137. }
  138. public static function url($filename)
  139. {
  140. File::tryFilename($filename);
  141. // FIXME: private site thumbnails?
  142. $path = common_config('thumbnail', 'path');
  143. if (empty($path)) {
  144. return File::url('thumb')."/{$filename}";
  145. }
  146. $protocol = (GNUsocial::useHTTPS() ? 'https' : 'http');
  147. $server = common_config('thumbnail', 'server') ?: common_config('site', 'server');
  148. if ($path[mb_strlen($path)-1] != '/') {
  149. $path .= '/';
  150. }
  151. if ($path[0] != '/') {
  152. $path = '/'.$path;
  153. }
  154. return $protocol.'://'.$server.$path.$filename;
  155. }
  156. public function getFilename()
  157. {
  158. return File::tryFilename($this->filename);
  159. }
  160. /**
  161. * @return string full filesystem path to the locally stored thumbnail file
  162. * @throws FileNotFoundException
  163. * @throws ServerException
  164. */
  165. public function getPath()
  166. {
  167. $oldpath = File::path($this->getFilename());
  168. $thumbpath = self::path($this->getFilename());
  169. // If we have a file in our old thumbnail storage path, move (or copy) it to the new one
  170. // (if the if/elseif don't match, we have a $thumbpath just as we should and can return it)
  171. if (file_exists($oldpath) && !file_exists($thumbpath)) {
  172. try {
  173. // let's get the filename of the File, to check below if it happens to be identical
  174. $file_filename = $this->getFile()->getFilename();
  175. } catch (NoResultException $e) {
  176. // reasonably the function calling us will handle the following as "File_thumbnail entry should be deleted"
  177. throw new FileNotFoundException($thumbpath);
  178. } catch (InvalidFilenameException $e) {
  179. // invalid filename in getFile()->getFilename(), just
  180. // means the File object isn't stored locally and that
  181. // means it's safe to move it below.
  182. $file_filename = null;
  183. }
  184. if ($this->getFilename() === $file_filename) {
  185. // special case where thumbnail file exactly matches stored File filename
  186. common_debug('File filename and File_thumbnail filename match on '.$this->file_id.', copying instead');
  187. copy($oldpath, $thumbpath);
  188. } elseif (!rename($oldpath, $thumbpath)) {
  189. common_log(LOG_ERR, 'Could not move thumbnail from '._ve($oldpath).' to '._ve($thumbpath));
  190. throw new ServerException('Could not move thumbnail from old path to new path.');
  191. } else {
  192. common_log(LOG_DEBUG, 'Moved thumbnail '.$this->file_id.' from '._ve($oldpath).' to '._ve($thumbpath));
  193. }
  194. } elseif (!file_exists($thumbpath)) {
  195. throw new FileNotFoundException($thumbpath);
  196. }
  197. return $thumbpath;
  198. }
  199. public function getUrl()
  200. {
  201. if (!empty($this->filename) || $this->getFile()->isLocal()) {
  202. // A locally stored File, so we can dynamically generate a URL.
  203. $url = common_local_url('attachment_thumbnail', array('attachment'=>$this->file_id));
  204. if (strpos($url, '?') === false) {
  205. $url .= '?';
  206. }
  207. return $url . http_build_query(array('w'=>$this->width, 'h'=>$this->height));
  208. }
  209. // No local filename available, return the remote URL we have stored
  210. return $this->url;
  211. }
  212. public function getHeight()
  213. {
  214. return $this->height;
  215. }
  216. public function getWidth()
  217. {
  218. return $this->width;
  219. }
  220. /**
  221. * @throws UseFileAsThumbnailException from File_thumbnail->getUrl() for stuff like animated GIFs
  222. */
  223. public function getHtmlAttrs(array $orig=array(), $overwrite=true)
  224. {
  225. $attrs = [ 'height' => $this->getHeight(),
  226. 'width' => $this->getWidth(),
  227. 'src' => $this->getUrl() ];
  228. return $overwrite ? array_merge($orig, $attrs) : array_merge($attrs, $orig);
  229. }
  230. public function delete($useWhere=false)
  231. {
  232. try {
  233. $thumbpath = self::path($this->getFilename());
  234. // if file does not exist, try to delete it
  235. $deleted = !file_exists($thumbpath) || @unlink($thumbpath);
  236. if (!$deleted) {
  237. common_log(LOG_ERR, 'Could not unlink existing thumbnail file: '._ve($thumbpath));
  238. }
  239. } catch (InvalidFilenameException $e) {
  240. common_log(LOG_ERR, 'Deleting object but not attempting deleting file: '._ve($e->getMessage()));
  241. }
  242. return parent::delete($useWhere);
  243. }
  244. public function getFile()
  245. {
  246. return File::getByID($this->file_id);
  247. }
  248. public function getFileId()
  249. {
  250. return $this->file_id;
  251. }
  252. public static function hashurl($url)
  253. {
  254. if (!mb_strlen($url)) {
  255. throw new Exception('No URL provided to hash algorithm.');
  256. }
  257. return hash(self::URLHASH_ALG, $url);
  258. }
  259. public function onInsert()
  260. {
  261. $this->setUrlhash();
  262. }
  263. public function onUpdate($dataObject=false)
  264. {
  265. // if we have nothing to compare with OR it has changed from previous entry
  266. if (!$dataObject instanceof Managed_DataObject || $this->url !== $dataObject->url) {
  267. $this->setUrlhash();
  268. }
  269. }
  270. public function setUrlhash()
  271. {
  272. $this->urlhash = mb_strlen($this->url)>0 ? self::hashurl($this->url) : null;
  273. }
  274. }