File_thumbnail.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  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; // datetime() 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' => 'datetime', 'not null' => true, 'default' => 'CURRENT_TIMESTAMP', 'description' => 'date this record was modified'),
  46. ),
  47. 'primary key' => array('file_id', 'width', 'height'),
  48. 'indexes' => array(
  49. 'file_thumbnail_file_id_idx' => array('file_id'),
  50. 'file_thumbnail_urlhash_idx' => array('urlhash'),
  51. ),
  52. 'foreign keys' => array(
  53. 'file_thumbnail_file_id_fkey' => array('file', array('file_id' => 'id')),
  54. )
  55. );
  56. }
  57. /**
  58. * Save oEmbed-provided thumbnail data
  59. *
  60. * @param object $data
  61. * @param int $file_id
  62. */
  63. public static function saveNew($data, $file_id)
  64. {
  65. if (!empty($data->thumbnail_url)) {
  66. // Non-photo types such as video will usually
  67. // show us a thumbnail, though it's not required.
  68. self::saveThumbnail(
  69. $file_id,
  70. $data->thumbnail_url,
  71. $data->thumbnail_width,
  72. $data->thumbnail_height
  73. );
  74. } elseif ($data->type == 'photo') {
  75. // The inline photo URL given should also fit within
  76. // our requested thumbnail size, per oEmbed spec.
  77. self::saveThumbnail(
  78. $file_id,
  79. $data->url,
  80. $data->width,
  81. $data->height
  82. );
  83. }
  84. }
  85. /**
  86. * Fetch an entry by using a File's id
  87. *
  88. * @param File $file The File object we're getting a thumbnail for.
  89. * @param boolean $notNullUrl Originally remote thumbnails have a URL stored, we use this to find the "original"
  90. *
  91. * @return File_thumbnail
  92. * @throws NoResultException if no File_thumbnail matched the criteria
  93. */
  94. public static function byFile(File $file, $notNullUrl = true)
  95. {
  96. $thumb = new File_thumbnail();
  97. $thumb->file_id = $file->getID();
  98. if ($notNullUrl) {
  99. $thumb->whereAdd('url IS NOT NULL');
  100. }
  101. $thumb->orderBy('modified ASC'); // the first created, a somewhat ugly hack
  102. $thumb->limit(1);
  103. if (!$thumb->find(true)) {
  104. throw new NoResultException($thumb);
  105. }
  106. return $thumb;
  107. }
  108. /**
  109. * Save a thumbnail record for the referenced file record.
  110. *
  111. * FIXME: Add error handling
  112. *
  113. * @param int $file_id
  114. * @param string $url
  115. * @param int $width
  116. * @param int $height
  117. */
  118. public static function saveThumbnail($file_id, $url, $width, $height, $filename = null)
  119. {
  120. $tn = new File_thumbnail;
  121. $tn->file_id = $file_id;
  122. $tn->url = $url;
  123. $tn->filename = $filename;
  124. $tn->width = intval($width);
  125. $tn->height = intval($height);
  126. $tn->insert();
  127. return $tn;
  128. }
  129. public static function path($filename)
  130. {
  131. File::tryFilename($filename);
  132. // NOTE: If this is left empty in default config, it will be set to File::path('thumb')
  133. $dir = common_config('thumbnail', 'dir');
  134. if (!in_array($dir[mb_strlen($dir)-1], ['/', '\\'])) {
  135. $dir .= DIRECTORY_SEPARATOR;
  136. }
  137. return $dir . $filename;
  138. }
  139. public static function url($filename)
  140. {
  141. File::tryFilename($filename);
  142. // FIXME: private site thumbnails?
  143. $path = common_config('thumbnail', 'path');
  144. if (empty($path)) {
  145. return File::url('thumb')."/{$filename}";
  146. }
  147. $protocol = (GNUsocial::useHTTPS() ? 'https' : 'http');
  148. $server = common_config('thumbnail', 'server') ?: common_config('site', 'server');
  149. if ($path[mb_strlen($path)-1] != '/') {
  150. $path .= '/';
  151. }
  152. if ($path[0] != '/') {
  153. $path = '/'.$path;
  154. }
  155. return $protocol.'://'.$server.$path.$filename;
  156. }
  157. public function getFilename()
  158. {
  159. return File::tryFilename($this->filename);
  160. }
  161. /**
  162. * @return string full filesystem path to the locally stored thumbnail file
  163. * @throws FileNotFoundException
  164. * @throws ServerException
  165. */
  166. public function getPath()
  167. {
  168. $oldpath = File::path($this->getFilename());
  169. $thumbpath = self::path($this->getFilename());
  170. // If we have a file in our old thumbnail storage path, move (or copy) it to the new one
  171. // (if the if/elseif don't match, we have a $thumbpath just as we should and can return it)
  172. if (file_exists($oldpath) && !file_exists($thumbpath)) {
  173. try {
  174. // let's get the filename of the File, to check below if it happens to be identical
  175. $file_filename = $this->getFile()->getFilename();
  176. } catch (NoResultException $e) {
  177. // reasonably the function calling us will handle the following as "File_thumbnail entry should be deleted"
  178. throw new FileNotFoundException($thumbpath);
  179. } catch (InvalidFilenameException $e) {
  180. // invalid filename in getFile()->getFilename(), just
  181. // means the File object isn't stored locally and that
  182. // means it's safe to move it below.
  183. $file_filename = null;
  184. }
  185. if ($this->getFilename() === $file_filename) {
  186. // special case where thumbnail file exactly matches stored File filename
  187. common_debug('File filename and File_thumbnail filename match on '.$this->file_id.', copying instead');
  188. copy($oldpath, $thumbpath);
  189. } elseif (!rename($oldpath, $thumbpath)) {
  190. common_log(LOG_ERR, 'Could not move thumbnail from '._ve($oldpath).' to '._ve($thumbpath));
  191. throw new ServerException('Could not move thumbnail from old path to new path.');
  192. } else {
  193. common_log(LOG_DEBUG, 'Moved thumbnail '.$this->file_id.' from '._ve($oldpath).' to '._ve($thumbpath));
  194. }
  195. } elseif (!file_exists($thumbpath)) {
  196. throw new FileNotFoundException($thumbpath);
  197. }
  198. return $thumbpath;
  199. }
  200. public function getUrl()
  201. {
  202. if (!empty($this->filename) || $this->getFile()->isLocal()) {
  203. // A locally stored File, so we can dynamically generate a URL.
  204. $url = common_local_url('attachment_thumbnail', array('attachment'=>$this->file_id));
  205. if (strpos($url, '?') === false) {
  206. $url .= '?';
  207. }
  208. return $url . http_build_query(array('w'=>$this->width, 'h'=>$this->height));
  209. }
  210. // No local filename available, return the remote URL we have stored
  211. return $this->url;
  212. }
  213. public function getHeight()
  214. {
  215. return $this->height;
  216. }
  217. public function getWidth()
  218. {
  219. return $this->width;
  220. }
  221. /**
  222. * @throws UseFileAsThumbnailException from File_thumbnail->getUrl() for stuff like animated GIFs
  223. */
  224. public function getHtmlAttrs(array $orig=array(), $overwrite=true)
  225. {
  226. $attrs = [ 'height' => $this->getHeight(),
  227. 'width' => $this->getWidth(),
  228. 'src' => $this->getUrl() ];
  229. return $overwrite ? array_merge($orig, $attrs) : array_merge($attrs, $orig);
  230. }
  231. public function delete($useWhere=false)
  232. {
  233. try {
  234. $thumbpath = self::path($this->getFilename());
  235. // if file does not exist, try to delete it
  236. $deleted = !file_exists($thumbpath) || @unlink($thumbpath);
  237. if (!$deleted) {
  238. common_log(LOG_ERR, 'Could not unlink existing thumbnail file: '._ve($thumbpath));
  239. }
  240. } catch (InvalidFilenameException $e) {
  241. common_log(LOG_ERR, 'Deleting object but not attempting deleting file: '._ve($e->getMessage()));
  242. }
  243. return parent::delete($useWhere);
  244. }
  245. public function getFile()
  246. {
  247. return File::getByID($this->file_id);
  248. }
  249. public function getFileId()
  250. {
  251. return $this->file_id;
  252. }
  253. public static function hashurl($url)
  254. {
  255. if (!mb_strlen($url)) {
  256. throw new Exception('No URL provided to hash algorithm.');
  257. }
  258. return hash(self::URLHASH_ALG, $url);
  259. }
  260. public function onInsert()
  261. {
  262. $this->setUrlhash();
  263. }
  264. public function onUpdate($dataObject=false)
  265. {
  266. // if we have nothing to compare with OR it has changed from previous entry
  267. if (!$dataObject instanceof Managed_DataObject || $this->url !== $dataObject->url) {
  268. $this->setUrlhash();
  269. }
  270. }
  271. public function setUrlhash()
  272. {
  273. $this->urlhash = mb_strlen($this->url)>0 ? self::hashurl($this->url) : null;
  274. }
  275. }