Attachment.php 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  1. <?php
  2. namespace common\modules\attachment\models;
  3. use common\modules\attachment\components\UploadedFile;
  4. use Yii;
  5. use yii\behaviors\BlameableBehavior;
  6. use yii\behaviors\TimestampBehavior;
  7. use yii\helpers\FileHelper;
  8. use yii\helpers\StringHelper;
  9. /**
  10. * This is the model class for table '{{%attachment}}'.
  11. *
  12. * @property integer $id
  13. * @property integer $user_id
  14. * @property string $name
  15. * @property string $title
  16. * @property string $path
  17. * @property string $extension
  18. * @property string $description
  19. * @property string $hash
  20. * @property integer $size
  21. * @property string $type
  22. * @property integer $created_at
  23. * @property integer $updated_at
  24. * @property string $url
  25. */
  26. class Attachment extends \yii\db\ActiveRecord
  27. {
  28. /**
  29. * @inheritdoc
  30. */
  31. public static function tableName()
  32. {
  33. return '{{%attachment}}';
  34. }
  35. /**
  36. * @inheritdoc
  37. */
  38. public function rules()
  39. {
  40. return [
  41. [['path', 'hash'], 'required'],
  42. [['user_id', 'size'], 'integer'],
  43. [['name', 'title', 'description', 'type', 'extension'], 'string', 'max' => 255],
  44. [['hash'], 'string', 'max' => 64],
  45. ];
  46. }
  47. /**
  48. * @inheritdoc
  49. */
  50. public function attributeLabels()
  51. {
  52. return [
  53. 'id' => 'ID',
  54. 'user_id' => 'User ID',
  55. 'name' => 'Name',
  56. 'title' => 'Title',
  57. 'description' => 'Description',
  58. 'hash' => 'Hash',
  59. 'size' => 'Size',
  60. 'type' => 'Type',
  61. 'created_at' => 'Created At',
  62. 'updated_at' => 'Updated At',
  63. ];
  64. }
  65. public function behaviors()
  66. {
  67. return [
  68. TimestampBehavior::className(),
  69. [
  70. 'class' => BlameableBehavior::className(),
  71. 'createdByAttribute' => 'user_id',
  72. 'updatedByAttribute' => false
  73. ]
  74. ];
  75. }
  76. public function fields()
  77. {
  78. return array_merge(parent::fields(), [
  79. 'url',
  80. 'isVideo' => function ($model) {
  81. if (false !== strpos($this->type, 'video')) {
  82. return true;
  83. }
  84. return false;
  85. },
  86. 'isImage' => function ($model) {
  87. if (false !== strpos($this->type, 'image')) {
  88. return true;
  89. }
  90. return false;
  91. },
  92. ]);
  93. }
  94. /**
  95. * @return string
  96. */
  97. public function getUrl()
  98. {
  99. return Yii::$app->storage->getUrl($this->path);
  100. }
  101. public function getThumb($width, $height, $options = [])
  102. {
  103. $width = (int)$width;
  104. $height = (int)$height;
  105. return Yii::$app->storage->thumbnail($this->path, $width, $height);
  106. }
  107. public function afterDelete()
  108. {
  109. parent::afterDelete();
  110. // 文件删了
  111. if (Yii::$app->storage->has($this->path)) {
  112. Yii::$app->storage->delete($this->path);
  113. }
  114. }
  115. /**
  116. * @param $hash
  117. * @return static|null
  118. */
  119. public static function findByHash($hash)
  120. {
  121. return static::findOne(['hash' => $hash]);
  122. }
  123. /**
  124. * @param $path
  125. * @param $file UploadedFile
  126. * @return Attachment|null|static
  127. * @throws \Exception
  128. */
  129. public static function uploadFromPost($path, $file)
  130. {
  131. $hash = md5_file($file->tempName);
  132. $attachment = static::findByHash($hash);
  133. // if (empty($attachment)) {
  134. if ($file->extension) {
  135. // 用hash当文件名,方便根据文件名查找
  136. $file->name = $hash . '.' . $file->extension;
  137. }
  138. // p($file->tempName);
  139. if ($filePath = Yii::$app->storage->putFile($path, $file)) {
  140. $attachment = new static();
  141. $attachment->path = $filePath;
  142. $attachment->name = $file->hashName;
  143. $attachment->extension = $file->extension;
  144. $attachment->type = $file->type;
  145. $attachment->size = $file->size;
  146. $attachment->hash = $hash;
  147. $attachment->save();
  148. } else {
  149. throw new \Exception('上传失败');
  150. }
  151. // }
  152. return $attachment;
  153. }
  154. /**
  155. * 抓取远程图片
  156. * @param $url
  157. * @return array(Attachment|null|static, string|null)
  158. */
  159. public static function uploadFromUrl($path, $url)
  160. {
  161. $hash = md5(file_get_contents($url));
  162. $attachment = static::findByHash($hash);
  163. $tempFile = Yii::getAlias('@storagePath/upload/' . $hash);
  164. file_put_contents($tempFile, file_get_contents($url));
  165. $mimeType = FileHelper::getMimeType($tempFile);
  166. $extension = current(FileHelper::getExtensionsByMimeType($mimeType, '@common/helpers/mimeTypes.php'));
  167. if (empty($attachment)) {
  168. $fileName = $hash . '.' . $extension;
  169. $filePath = ($path ? ($path . '/') : '') . $fileName;
  170. $fileSize = filesize($tempFile);
  171. if (Yii::$app->storage->put($filePath, file_get_contents($tempFile))) {
  172. @unlink($tempFile);
  173. $attachment = new static();
  174. $attachment->path = $filePath;
  175. $attachment->name = $fileName;
  176. $attachment->extension = $extension;
  177. $attachment->type = $mimeType;
  178. $attachment->size = $fileSize;
  179. $attachment->hash = $hash;
  180. $attachment->save();
  181. } else {
  182. return [null, '上传失败'];
  183. }
  184. }
  185. return [$attachment, null];
  186. }
  187. /**
  188. * 上传stream二进制数据流文件
  189. * @param $url
  190. * @return array(Attachment|null|static, string|null)
  191. */
  192. public static function uploadFromStream($stream, $path = null)
  193. {
  194. if ($path == null) {
  195. $path = date('Ymd');
  196. }
  197. $hash = md5($stream);
  198. $attachment = static::findByHash($hash);
  199. $tempFile = Yii::getAlias('@storagePath/upload/' . $hash);
  200. file_put_contents($tempFile, $stream);
  201. $mimeType = FileHelper::getMimeType($tempFile);
  202. if (!$mimeType) {
  203. $mimeType = 'image/jpeg';
  204. $extension = 'jpg';
  205. } else {
  206. $extension = current(FileHelper::getExtensionsByMimeType($mimeType, '@common/helpers/mimeTypes.php'));
  207. if (!$extension || empty($extension)) {
  208. $mimeType = 'image/jpeg';
  209. $extension = 'jpg';
  210. }
  211. }
  212. if (empty($attachment)) {
  213. $fileName = $hash . '.' . $extension;
  214. $filePath = ($path ? ($path . '/') : '') . $fileName;
  215. $fileSize = filesize($tempFile);
  216. if (Yii::$app->storage->put($filePath, file_get_contents($tempFile))) {
  217. @unlink($tempFile);
  218. $attachment = new static();
  219. $attachment->path = $filePath;
  220. $attachment->name = $fileName;
  221. $attachment->extension = $extension;
  222. $attachment->type = $mimeType;
  223. $attachment->size = $fileSize;
  224. $attachment->hash = $hash;
  225. $attachment->save(false);
  226. } else {
  227. return [null, '上传失败'];
  228. }
  229. }
  230. return [$attachment, null];
  231. }
  232. /**
  233. * 从临时文件上传
  234. * @param $path
  235. * @param $tempFile
  236. * @return array
  237. * @throws \yii\base\InvalidConfigException
  238. * @author nodelog
  239. */
  240. public static function uploadFromFile($path, $tempFile)
  241. {
  242. $hash = md5(file_get_contents($tempFile));
  243. $attachment = static::findByHash($hash);
  244. $mimeType = FileHelper::getMimeType($tempFile);
  245. $extension = current(FileHelper::getExtensionsByMimeType($mimeType, '@common/helpers/mimeTypes.php'));
  246. if (empty($attachment)) {
  247. $fileName = $hash . '.' . $extension;
  248. $filePath = ($path ? ($path . '/') : '') . $fileName;
  249. $fileSize = filesize($tempFile);
  250. if (Yii::$app->storage->put($filePath, file_get_contents($tempFile))) {
  251. @unlink($tempFile);
  252. $attachment = new static();
  253. $attachment->path = $filePath;
  254. $attachment->name = $fileName;
  255. $attachment->extension = $extension;
  256. $attachment->type = $mimeType;
  257. $attachment->size = $fileSize;
  258. $attachment->hash = $hash;
  259. $attachment->save();
  260. } else {
  261. return [null, '上传失败'];
  262. }
  263. }
  264. return [$attachment, null];
  265. }
  266. public function makeCropStorage($width, $height, $x, $y)
  267. {
  268. $url = Yii::$app->storage->crop($this->path, $width, $height, [$x, $y]);
  269. return self::uploadFromUrl($this->path, $url);
  270. }
  271. public function __toString()
  272. {
  273. return $this->getUrl();
  274. }
  275. }