PageRenderTime 52ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 1ms

/protected/modules/fileManager/models/FileManager.php

https://bitbucket.org/graaaf/erso
PHP | 411 lines | 311 code | 90 blank | 10 comment | 19 complexity | 946bbb16460fe32b26a38e9093c71381 MD5 | raw file
Possible License(s): GPL-3.0, LGPL-3.0, LGPL-2.1, BSD-3-Clause, BSD-2-Clause
  1. <?php
  2. class FileManager extends ActiveRecordModel
  3. {
  4. const UPLOAD_PATH = 'upload/fileManager';
  5. const FILE_POSTFIX = '';
  6. public $extension;
  7. public $size;
  8. public $error;
  9. public function name()
  10. {
  11. return 'Файловый менеджер';
  12. }
  13. public static function model($className = __CLASS__)
  14. {
  15. return parent::model($className);
  16. }
  17. public function tableName()
  18. {
  19. return 'file_manager';
  20. }
  21. public function primaryKey()
  22. {
  23. return 'id';
  24. }
  25. public function rules()
  26. {
  27. return array(
  28. array(
  29. 'path', 'length',
  30. 'min' => 1
  31. ), array(
  32. 'nameWithoutExt', 'length',
  33. 'min' => 1,
  34. 'max' => 900,
  35. 'tooShort' => 'Название файла должно быть меньше 1 сим.',
  36. 'tooLong' => 'Пожалуйста, сократите наименование файла до 900 сим.'
  37. )
  38. );
  39. }
  40. public function behaviors()
  41. {
  42. return array(// 'sortable' => array(
  43. // 'class' => 'application.components.activeRecordBehaviors.SortableBehavior'
  44. // )
  45. );
  46. }
  47. public function parent($model_id, $id)
  48. {
  49. $alias = $this->getTableAlias();
  50. $this->getDbCriteria()->mergeWith(array(
  51. 'condition' => "$alias.model_id='$model_id' AND $alias.object_id='$id'",
  52. 'order' => "$alias.order DESC"
  53. ));
  54. return $this;
  55. }
  56. public function tag($tag)
  57. {
  58. $alias = $this->getTableAlias();
  59. $this->getDbCriteria()->mergeWith(array(
  60. 'condition' => "$alias.tag='$tag'"
  61. ));
  62. return $this;
  63. }
  64. public function getDeleteUrl()
  65. {
  66. return Yii::app()->controller->url('fileManagerAdmin/delete', array('id' => $this->id));
  67. }
  68. public function setExt($val)
  69. {
  70. $this->extension = $val;
  71. $this->mimeType = $this->mimeByExt($val);
  72. }
  73. public function getIsImage()
  74. {
  75. return in_array($this->extension, array(
  76. 'png', 'jpeg', 'jpg', 'tiff', 'ief', 'gif'
  77. ));
  78. }
  79. public function getIsSound()
  80. {
  81. return in_array($this->extension, array(
  82. 'wma', 'mp3'
  83. ));
  84. }
  85. public function getIsExcel()
  86. {
  87. return in_array($this->extension, array(
  88. 'xl', 'xla', 'xlb', 'xlc', 'xld', 'xlk', 'xll', 'xlm', 'xls', 'xlt', 'xlv', 'xlw'
  89. ));
  90. }
  91. public function getIsWord()
  92. {
  93. return in_array($this->extension, array(
  94. 'doc', 'dot', 'docx'
  95. ));
  96. }
  97. public function getIsFileExist()
  98. {
  99. $filename = Yii::app()->getBasePath() . '/../' . $this->path . '/' . $this->name;
  100. return file_exists($filename) && is_file($filename);
  101. }
  102. public function getIsArchive()
  103. {
  104. return in_array($this->extension, array(
  105. 'zip', 'rar', 'tar', 'gz'
  106. ));
  107. }
  108. public function getIcon()
  109. {
  110. $folder = Yii::app()->getModule('fileManager')->assetsUrl() . '/img/fileIcons/';
  111. if ($this->isImage)
  112. {
  113. $name = 'image';
  114. }
  115. // elseif ($this->isSound)
  116. // {
  117. // $name = 'sound';
  118. // }
  119. elseif ($this->isExcel)
  120. {
  121. $name = 'excel';
  122. } elseif ($this->isWord)
  123. {
  124. $name = 'word';
  125. } elseif ($this->isArchive)
  126. {
  127. $name = 'rar';
  128. } elseif (is_file('.' . $folder . $this->extension . '.jpg'))
  129. {
  130. $name = $this->extension;
  131. } else
  132. {
  133. $name = 'any';
  134. }
  135. return CHtml::image($folder . $name . '.jpg', '', array('height' => 48));
  136. }
  137. public function getHandler($field = false)
  138. {
  139. Yii::import('application.modules.fileManager.extensions.upload.Upload');
  140. $param = $field ? $_FILES[$field] : self::UPLOAD_PATH . $this->name;
  141. return new Upload($param);
  142. }
  143. public function save($useWatermark=false, $attributes=NULL)
  144. {
  145. if (!parent::save())
  146. {
  147. $this->error = Yii::t('FileManagerModule.main', 'Не удалось сохранить изменения');
  148. return false;
  149. }
  150. if ($this->model_id == 'Portfolio')
  151. {
  152. Yii::import('application.modules.fileManager.extensions.upload.Upload');
  153. $image_class = new Upload($this->getServerPath());
  154. if ($useWatermark) {
  155. $image_class->image_watermark = MODULES_PATH . 'fileManager/assets/mark.png';
  156. $image_class->image_watermark_x = -24;
  157. $image_class->image_watermark_y = -24;
  158. }
  159. file_put_contents($this->getServerPath(), $image_class->process());
  160. }
  161. return true;
  162. }
  163. public static function str2url($str)
  164. {
  165. $str = self::rus2translit($str); // переводим в транслит
  166. $str = mb_strtolower($str); // в нижний регистр
  167. $str = preg_replace('~[^-a-z0-9_\s]+~u', '-', $str); // заменям все ненужное нам на "-"
  168. $str = trim($str, "-"); // удаляем начальные и конечные '-'
  169. return $str;
  170. }
  171. public function setExtraProperties($field, &$handler, $options)
  172. {
  173. $info = getimagesize($_FILES[$field]['tmp_name']);
  174. if (isset($options['save_y']) && $options['save_y'])
  175. {
  176. $size = isset($options['min_y']) ? $options['min_y'] : 0;
  177. $handler->image_y = ($info[1] > $size) ? $info[1] : $size;
  178. }
  179. if (isset($options['save_x']) && $options['save_x'])
  180. {
  181. $size = isset($options['min_x']) ? $options['min_x'] : 0;
  182. $handler->image_x = ($info[0] > $size) ? $info[0] : $size;
  183. }
  184. }
  185. public function saveFile()
  186. {
  187. $file = CUploadedFile::getInstanceByName('file');
  188. // $file_name = FileSystem::vaultResolveCollision(self::UPLOAD_PATH, $file->name);
  189. $file_name = $file->name;
  190. $file_ext = end(explode('.', $file_name));
  191. $new_name = md5($file_name . time()) . '.' . $file_ext;
  192. $new_file = self::UPLOAD_PATH . '/' . ($new_name);
  193. if ($file->saveAs('./' . $new_file))
  194. {
  195. list($this->path, $this->name) = FileSystem::moveToVault($new_file, self::UPLOAD_PATH, true);
  196. $this->title = $file_name;
  197. $this->name = $new_name;
  198. $this->fill();
  199. return true;
  200. } else
  201. {
  202. $this->error = $file->getError();
  203. return false;
  204. }
  205. }
  206. /**
  207. * @return string formatted file size
  208. */
  209. public function getFormatSize()
  210. {
  211. $size = $this->size;
  212. $metrics[0] = 'байт';
  213. $metrics[1] = 'кб.';
  214. $metrics[2] = 'мб.';
  215. $metrics[3] = 'гб.';
  216. $metric = 0;
  217. while (floor($size / 1024) > 0)
  218. {
  219. ++$metric;
  220. $size /= 1024;
  221. }
  222. $ret = round($size, 1) . " " . (isset($metrics[$metric]) ? $metrics[$metric] : '??');
  223. return $ret;
  224. }
  225. public function afterFind()
  226. {
  227. parent::afterFind();
  228. $this->fill();
  229. }
  230. public function fill()
  231. {
  232. $file = Yii::app()->getBasePath() . '/../' . $this->path . '/' . $this->name;
  233. $this->size = is_file($file) ? filesize($file) : NULL; //$this->formatSize($this->basePath.$this->name);
  234. $this->size = $this->getFormatSize();
  235. $this->extension = pathinfo($this->name, PATHINFO_EXTENSION);
  236. }
  237. public function getNameWithoutExt()
  238. {
  239. $name = pathinfo($this->name, PATHINFO_FILENAME);
  240. $params = array(' ' => '');
  241. if (self::FILE_POSTFIX)
  242. {
  243. $params[self::FILE_POSTFIX] = '';
  244. }
  245. return strtr($name, $params);
  246. }
  247. public function beforeSave()
  248. {
  249. if (parent::beforeSave())
  250. {
  251. if ($this->isNewRecord)
  252. {
  253. $model = FileManager::model()->parent($this->model_id, $this->object_id)->limit(1)
  254. ->find();
  255. $this->order = $model ? $model->order + 1 : 1;
  256. $this->title;
  257. }
  258. return true;
  259. } else
  260. {
  261. return false;
  262. }
  263. }
  264. public function beforeDelete()
  265. {
  266. if (parent::beforeDelete())
  267. {
  268. if (is_file(self::UPLOAD_PATH . $this->name))
  269. {
  270. FileSystem::deleteFileWithSimilarNames(self::UPLOAD_PATH . '/crop', $this->name);
  271. FileSystem::deleteFileWithSimilarNames(self::UPLOAD_PATH . '/watermark', $this->name);
  272. @unlink('./' . self::UPLOAD_PATH . $this->name);
  273. }
  274. return true;
  275. }
  276. return false;
  277. }
  278. public function search($crit = null)
  279. {
  280. $criteria = new CDbCriteria;
  281. $criteria->compare('object_id', $this->object_id, true);
  282. $criteria->compare('model_id', $this->model_id, true);
  283. $criteria->compare('tag', $this->tag, true);
  284. $criteria->compare('title', $this->title, true);
  285. $criteria->compare('descr', $this->descr, true);
  286. $criteria->compare('order', $this->order);
  287. if ($crit)
  288. {
  289. $criteria->mergeWith($crit);
  290. }
  291. return new ActiveDataProvider(get_class($this), array(
  292. 'criteria' => $criteria
  293. ));
  294. }
  295. public function getContent()
  296. {
  297. if (file_exists($this->path))
  298. {
  299. return file_get_contents($this->path . '/' . $this->name);
  300. }
  301. }
  302. public function getDownloadUrl()
  303. {
  304. $hash = $this->getHash();
  305. return Yii::app()->getController()->createUrl('/fileManager/fileManager/downloadFile', array(
  306. 'hash' => "{$hash}x{$this->id}",
  307. ));
  308. }
  309. public function getHash()
  310. {
  311. return md5($this->object_id . $this->model_id . $this->name . $this->tag);
  312. }
  313. public function getHref()
  314. {
  315. return $this->getDownloadUrl();
  316. }
  317. public function getServerPath()
  318. {
  319. return $_SERVER['DOCUMENT_ROOT'] . $this->path . '/' . $this->name;
  320. }
  321. }