PageRenderTime 79ms CodeModel.GetById 31ms RepoModel.GetById 1ms app.codeStats 0ms

/php/elFinderVolumeDriver.class.php

https://github.com/dyjo/elFinder
PHP | 3482 lines | 1730 code | 497 blank | 1255 comment | 516 complexity | 597f85ac3fbdfa7feec4ea086772fd10 MD5 | raw file
  1. <?php
  2. /**
  3. * Base class for elFinder volume.
  4. * Provide 2 layers:
  5. * 1. Public API (commands)
  6. * 2. abstract fs API
  7. *
  8. * All abstract methods begin with "_"
  9. *
  10. * @author Dmitry (dio) Levashov
  11. * @author Troex Nevelin
  12. * @author Alexey Sukhotin
  13. **/
  14. abstract class elFinderVolumeDriver {
  15. /**
  16. * Driver id
  17. * Must be started from letter and contains [a-z0-9]
  18. * Used as part of volume id
  19. *
  20. * @var string
  21. **/
  22. protected $driverId = 'a';
  23. /**
  24. * Volume id - used as prefix for files hashes
  25. *
  26. * @var string
  27. **/
  28. protected $id = '';
  29. /**
  30. * Flag - volume "mounted" and available
  31. *
  32. * @var bool
  33. **/
  34. protected $mounted = false;
  35. /**
  36. * Root directory path
  37. *
  38. * @var string
  39. **/
  40. protected $root = '';
  41. /**
  42. * Root basename | alias
  43. *
  44. * @var string
  45. **/
  46. protected $rootName = '';
  47. /**
  48. * Default directory to open
  49. *
  50. * @var string
  51. **/
  52. protected $startPath = '';
  53. /**
  54. * Base URL
  55. *
  56. * @var string
  57. **/
  58. protected $URL = '';
  59. /**
  60. * Thumbnails dir path
  61. *
  62. * @var string
  63. **/
  64. protected $tmbPath = '';
  65. /**
  66. * Is thumbnails dir writable
  67. *
  68. * @var bool
  69. **/
  70. protected $tmbPathWritable = false;
  71. /**
  72. * Thumbnails base URL
  73. *
  74. * @var string
  75. **/
  76. protected $tmbURL = '';
  77. /**
  78. * Thumbnails size in px
  79. *
  80. * @var int
  81. **/
  82. protected $tmbSize = 48;
  83. /**
  84. * Image manipulation lib name
  85. * auto|imagick|mogtify|gd
  86. *
  87. * @var string
  88. **/
  89. protected $imgLib = 'auto';
  90. /**
  91. * Library to crypt files name
  92. *
  93. * @var string
  94. **/
  95. protected $cryptLib = '';
  96. /**
  97. * Archivers config
  98. *
  99. * @var array
  100. **/
  101. protected $archivers = array(
  102. 'create' => array(),
  103. 'extract' => array()
  104. );
  105. /**
  106. * How many subdirs levels return for tree
  107. *
  108. * @var int
  109. **/
  110. protected $treeDeep = 1;
  111. /**
  112. * Errors from last failed action
  113. *
  114. * @var array
  115. **/
  116. protected $error = array();
  117. /**
  118. * Today 24:00 timestamp
  119. *
  120. * @var int
  121. **/
  122. protected $today = 0;
  123. /**
  124. * Yesterday 24:00 timestamp
  125. *
  126. * @var int
  127. **/
  128. protected $yesterday = 0;
  129. /**
  130. * Object configuration
  131. *
  132. * @var array
  133. **/
  134. protected $options = array(
  135. 'id' => '',
  136. // root directory path
  137. 'path' => '',
  138. // open this path on initial request instead of root path
  139. 'startPath' => '',
  140. // how many subdirs levels return per request
  141. 'treeDeep' => 1,
  142. // root url, not set to disable sending URL to client (replacement for old "fileURL" option)
  143. 'URL' => '',
  144. // directory separator. required by client to show paths correctly
  145. 'separator' => DIRECTORY_SEPARATOR,
  146. // library to crypt/uncrypt files names (not implemented)
  147. 'cryptLib' => '',
  148. // how to detect files mimetypes. (auto/internal/finfo/mime_content_type)
  149. 'mimeDetect' => 'auto',
  150. // mime.types file path (for mimeDetect==internal)
  151. 'mimefile' => '',
  152. // directory for thumbnails
  153. 'tmbPath' => '.tmb',
  154. // mode to create thumbnails dir
  155. 'tmbPathMode' => 0777,
  156. // thumbnails dir URL. Set it if store thumbnails outside root directory
  157. 'tmbURL' => '',
  158. // thumbnails size (px)
  159. 'tmbSize' => 48,
  160. // thumbnails crop (true - crop, false - scale image to fit thumbnail size)
  161. 'tmbCrop' => true,
  162. // thumbnails background color (hex #rrggbb or 'transparent')
  163. 'tmbBgColor' => '#ffffff',
  164. // image manipulations library
  165. 'imgLib' => 'auto',
  166. // on paste file - if true - old file will be replaced with new one, if false new file get name - original_name-number.ext
  167. 'copyOverwrite' => true,
  168. // if true - join new and old directories content on paste
  169. 'copyJoin' => true,
  170. // on upload - if true - old file will be replaced with new one, if false new file get name - original_name-number.ext
  171. 'uploadOverwrite' => true,
  172. // mimetypes allowed to upload
  173. 'uploadAllow' => array(),
  174. // mimetypes not allowed to upload
  175. 'uploadDeny' => array(),
  176. // order to proccess uploadAllow and uploadDeny options
  177. 'uploadOrder' => array('deny', 'allow'),
  178. // maximum upload file size. NOTE - this is size for every uploaded files
  179. 'uploadMaxSize' => 0,
  180. // files dates format
  181. 'dateFormat' => 'j M Y H:i',
  182. // files time format
  183. 'timeFormat' => 'H:i',
  184. // if true - every folder will be check for children folders, otherwise all folders will be marked as having subfolders
  185. 'checkSubfolders' => true,
  186. // allow to copy from this volume to other ones?
  187. 'copyFrom' => true,
  188. // allow to copy from other volumes to this one?
  189. 'copyTo' => true,
  190. // list of commands disabled on this root
  191. 'disabled' => array(),
  192. // regexp or function name to validate new file name
  193. 'acceptedName' => '/^[^\.].*/', //<-- DONT touch this! Use constructor options to overwrite it!
  194. // function/class method to control files permissions
  195. 'accessControl' => null,
  196. // some data required by access control
  197. 'accessControlData' => null,
  198. // default permissions. not set hidden/locked here - take no effect
  199. 'defaults' => array(
  200. 'read' => true,
  201. 'write' => true
  202. ),
  203. // files attributes
  204. 'attributes' => array(),
  205. // Allowed archive's mimetypes to create. Leave empty for all available types.
  206. 'archiveMimes' => array(),
  207. // Manual config for archivers. See example below. Leave empty for auto detect
  208. 'archivers' => array(),
  209. // required to fix bug on macos
  210. 'utf8fix' => false,
  211. // й ё Й Ё Ø Å
  212. 'utf8patterns' => array("\u0438\u0306", "\u0435\u0308", "\u0418\u0306", "\u0415\u0308", "\u00d8A", "\u030a"),
  213. 'utf8replace' => array("\u0439", "\u0451", "\u0419", "\u0401", "\u00d8", "\u00c5")
  214. );
  215. /**
  216. * Defaults permissions
  217. *
  218. * @var array
  219. **/
  220. protected $defaults = array(
  221. 'read' => true,
  222. 'write' => true,
  223. 'locked' => false,
  224. 'hidden' => false
  225. );
  226. /**
  227. * Access control function/class
  228. *
  229. * @var mixed
  230. **/
  231. protected $attributes = array();
  232. /**
  233. * Access control function/class
  234. *
  235. * @var mixed
  236. **/
  237. protected $access = null;
  238. /**
  239. * Mime types allowed to upload
  240. *
  241. * @var array
  242. **/
  243. protected $uploadAllow = array();
  244. /**
  245. * Mime types denied to upload
  246. *
  247. * @var array
  248. **/
  249. protected $uploadDeny = array();
  250. /**
  251. * Order to validate uploadAllow and uploadDeny
  252. *
  253. * @var array
  254. **/
  255. protected $uploadOrder = array();
  256. /**
  257. * Maximum allowed upload file size.
  258. * Set as number or string with unit - "10M", "500K", "1G"
  259. *
  260. * @var int|string
  261. **/
  262. protected $uploadMaxSize = 0;
  263. /**
  264. * Mimetype detect method
  265. *
  266. * @var string
  267. **/
  268. protected $mimeDetect = 'auto';
  269. /**
  270. * Flag - mimetypes from externail file was loaded
  271. *
  272. * @var bool
  273. **/
  274. private static $mimetypesLoaded = false;
  275. /**
  276. * Finfo object for mimeDetect == 'finfo'
  277. *
  278. * @var object
  279. **/
  280. protected $finfo = null;
  281. /**
  282. * List of disabled client's commands
  283. *
  284. * @var array
  285. **/
  286. protected $diabled = array();
  287. /**
  288. * default extensions/mimetypes for mimeDetect == 'internal'
  289. *
  290. * @var array
  291. **/
  292. protected static $mimetypes = array(
  293. // applications
  294. 'ai' => 'application/postscript',
  295. 'eps' => 'application/postscript',
  296. 'exe' => 'application/x-executable',
  297. 'doc' => 'application/vnd.ms-word',
  298. 'xls' => 'application/vnd.ms-excel',
  299. 'ppt' => 'application/vnd.ms-powerpoint',
  300. 'pps' => 'application/vnd.ms-powerpoint',
  301. 'pdf' => 'application/pdf',
  302. 'xml' => 'application/xml',
  303. 'swf' => 'application/x-shockwave-flash',
  304. 'torrent' => 'application/x-bittorrent',
  305. 'jar' => 'application/x-jar',
  306. // open office (finfo detect as application/zip)
  307. 'odt' => 'application/vnd.oasis.opendocument.text',
  308. 'ott' => 'application/vnd.oasis.opendocument.text-template',
  309. 'oth' => 'application/vnd.oasis.opendocument.text-web',
  310. 'odm' => 'application/vnd.oasis.opendocument.text-master',
  311. 'odg' => 'application/vnd.oasis.opendocument.graphics',
  312. 'otg' => 'application/vnd.oasis.opendocument.graphics-template',
  313. 'odp' => 'application/vnd.oasis.opendocument.presentation',
  314. 'otp' => 'application/vnd.oasis.opendocument.presentation-template',
  315. 'ods' => 'application/vnd.oasis.opendocument.spreadsheet',
  316. 'ots' => 'application/vnd.oasis.opendocument.spreadsheet-template',
  317. 'odc' => 'application/vnd.oasis.opendocument.chart',
  318. 'odf' => 'application/vnd.oasis.opendocument.formula',
  319. 'odb' => 'application/vnd.oasis.opendocument.database',
  320. 'odi' => 'application/vnd.oasis.opendocument.image',
  321. 'oxt' => 'application/vnd.openofficeorg.extension',
  322. // MS office 2007 (finfo detect as application/zip)
  323. 'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
  324. 'docm' => 'application/vnd.ms-word.document.macroEnabled.12',
  325. 'dotx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.template',
  326. 'dotm' => 'application/vnd.ms-word.template.macroEnabled.12',
  327. 'xlsx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
  328. 'xlsm' => 'application/vnd.ms-excel.sheet.macroEnabled.12',
  329. 'xltx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.template',
  330. 'xltm' => 'application/vnd.ms-excel.template.macroEnabled.12',
  331. 'xlsb' => 'application/vnd.ms-excel.sheet.binary.macroEnabled.12',
  332. 'xlam' => 'application/vnd.ms-excel.addin.macroEnabled.12',
  333. 'pptx' => 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
  334. 'pptm' => 'application/vnd.ms-powerpoint.presentation.macroEnabled.12',
  335. 'ppsx' => 'application/vnd.openxmlformats-officedocument.presentationml.slideshow',
  336. 'ppsm' => 'application/vnd.ms-powerpoint.slideshow.macroEnabled.12',
  337. 'potx' => 'application/vnd.openxmlformats-officedocument.presentationml.template',
  338. 'potm' => 'application/vnd.ms-powerpoint.template.macroEnabled.12',
  339. 'ppam' => 'application/vnd.ms-powerpoint.addin.macroEnabled.12',
  340. 'sldx' => 'application/vnd.openxmlformats-officedocument.presentationml.slide',
  341. 'sldm' => 'application/vnd.ms-powerpoint.slide.macroEnabled.12',
  342. // archives
  343. 'gz' => 'application/x-gzip',
  344. 'tgz' => 'application/x-gzip',
  345. 'bz' => 'application/x-bzip2',
  346. 'bz2' => 'application/x-bzip2',
  347. 'tbz' => 'application/x-bzip2',
  348. 'zip' => 'application/zip',
  349. 'rar' => 'application/x-rar',
  350. 'tar' => 'application/x-tar',
  351. '7z' => 'application/x-7z-compressed',
  352. // texts
  353. 'txt' => 'text/plain',
  354. 'php' => 'text/x-php',
  355. 'html' => 'text/html',
  356. 'htm' => 'text/html',
  357. 'js' => 'text/javascript',
  358. 'css' => 'text/css',
  359. 'rtf' => 'text/rtf',
  360. 'rtfd' => 'text/rtfd',
  361. 'py' => 'text/x-python',
  362. 'java' => 'text/x-java-source',
  363. 'rb' => 'text/x-ruby',
  364. 'sh' => 'text/x-shellscript',
  365. 'pl' => 'text/x-perl',
  366. 'xml' => 'text/xml',
  367. 'sql' => 'text/x-sql',
  368. 'c' => 'text/x-csrc',
  369. 'h' => 'text/x-chdr',
  370. 'cpp' => 'text/x-c++src',
  371. 'hh' => 'text/x-c++hdr',
  372. 'log' => 'text/plain',
  373. 'csv' => 'text/x-comma-separated-values',
  374. // images
  375. 'bmp' => 'image/x-ms-bmp',
  376. 'jpg' => 'image/jpeg',
  377. 'jpeg' => 'image/jpeg',
  378. 'gif' => 'image/gif',
  379. 'png' => 'image/png',
  380. 'tif' => 'image/tiff',
  381. 'tiff' => 'image/tiff',
  382. 'tga' => 'image/x-targa',
  383. 'psd' => 'image/vnd.adobe.photoshop',
  384. 'ai' => 'image/vnd.adobe.photoshop',
  385. 'xbm' => 'image/xbm',
  386. 'pxm' => 'image/pxm',
  387. //audio
  388. 'mp3' => 'audio/mpeg',
  389. 'mid' => 'audio/midi',
  390. 'ogg' => 'audio/ogg',
  391. 'oga' => 'audio/ogg',
  392. 'm4a' => 'audio/x-m4a',
  393. 'wav' => 'audio/wav',
  394. 'wma' => 'audio/x-ms-wma',
  395. // video
  396. 'avi' => 'video/x-msvideo',
  397. 'dv' => 'video/x-dv',
  398. 'mp4' => 'video/mp4',
  399. 'mpeg' => 'video/mpeg',
  400. 'mpg' => 'video/mpeg',
  401. 'mov' => 'video/quicktime',
  402. 'wm' => 'video/x-ms-wmv',
  403. 'flv' => 'video/x-flv',
  404. 'mkv' => 'video/x-matroska',
  405. 'webm' => 'video/webm',
  406. 'ogv' => 'video/ogg',
  407. 'ogm' => 'video/ogg'
  408. );
  409. /**
  410. * Directory separator - required by client
  411. *
  412. * @var string
  413. **/
  414. protected $separator = DIRECTORY_SEPARATOR;
  415. /**
  416. * Mimetypes allowed to display
  417. *
  418. * @var array
  419. **/
  420. protected $onlyMimes = array();
  421. /**
  422. * Store files moved or overwrited files info
  423. *
  424. * @var array
  425. **/
  426. protected $removed = array();
  427. /**
  428. * Cache storage
  429. *
  430. * @var array
  431. **/
  432. protected $cache = array();
  433. /**
  434. * Cache by folders
  435. *
  436. * @var array
  437. **/
  438. protected $dirsCache = array();
  439. /*********************************************************************/
  440. /* INITIALIZATION */
  441. /*********************************************************************/
  442. /**
  443. * Prepare driver before mount volume.
  444. * Return true if volume is ready.
  445. *
  446. * @return bool
  447. * @author Dmitry (dio) Levashov
  448. **/
  449. protected function init() {
  450. return true;
  451. }
  452. /**
  453. * Configure after successfull mount.
  454. * By default set thumbnails path and image manipulation library.
  455. *
  456. * @return void
  457. * @author Dmitry (dio) Levashov
  458. **/
  459. protected function configure() {
  460. // set thumbnails path
  461. $path = $this->options['tmbPath'];
  462. if ($path) {
  463. if (!file_exists($path)) {
  464. if (@mkdir($path)) {
  465. chmod($path, $this->options['tmbPathMode']);
  466. } else {
  467. $path = '';
  468. }
  469. }
  470. if (is_dir($path) && is_readable($path)) {
  471. $this->tmbPath = $path;
  472. $this->tmbPathWritable = is_writable($path);
  473. }
  474. }
  475. // set image manipulation library
  476. $type = preg_match('/^(imagick|gd|auto)$/i', $this->options['imgLib'])
  477. ? strtolower($this->options['imgLib'])
  478. : 'auto';
  479. if (($type == 'imagick' || $type == 'auto') && extension_loaded('imagick')) {
  480. $this->imgLib = 'imagick';
  481. } else {
  482. $this->imgLib = function_exists('gd_info') ? 'gd' : '';
  483. }
  484. }
  485. /*********************************************************************/
  486. /* PUBLIC API */
  487. /*********************************************************************/
  488. /**
  489. * Return driver id. Used as a part of volume id.
  490. *
  491. * @return string
  492. * @author Dmitry (dio) Levashov
  493. **/
  494. public function driverId() {
  495. return $this->driverId;
  496. }
  497. /**
  498. * Return volume id
  499. *
  500. * @return string
  501. * @author Dmitry (dio) Levashov
  502. **/
  503. public function id() {
  504. return $this->id;
  505. }
  506. /**
  507. * Return debug info for client
  508. *
  509. * @return array
  510. * @author Dmitry (dio) Levashov
  511. **/
  512. public function debug() {
  513. return array(
  514. 'id' => $this->id(),
  515. 'name' => strtolower(substr(get_class($this), strlen('elfinderdriver'))),
  516. 'mimeDetect' => $this->mimeDetect,
  517. 'imgLib' => $this->imgLib
  518. );
  519. }
  520. /**
  521. * "Mount" volume.
  522. * Return true if volume available for read or write,
  523. * false - otherwise
  524. *
  525. * @return bool
  526. * @author Dmitry (dio) Levashov
  527. * @author Alexey Sukhotin
  528. **/
  529. public function mount(array $opts) {
  530. if (!isset($opts['path']) || $opts['path'] === '') {
  531. return $this->setError('Path undefined.');;
  532. }
  533. $this->options = array_merge($this->options, $opts);
  534. $this->id = $this->driverId.(!empty($this->options['id']) ? $this->options['id'] : elFinder::$volumesCnt++).'_';
  535. $this->root = $this->_normpath($this->options['path']);
  536. $this->separator = isset($this->options['separator']) ? $this->options['separator'] : DIRECTORY_SEPARATOR;
  537. // default file attribute
  538. $this->defaults = array(
  539. 'read' => isset($this->options['defaults']['read']) ? !!$this->options['defaults']['read'] : true,
  540. 'write' => isset($this->options['defaults']['write']) ? !!$this->options['defaults']['write'] : true,
  541. 'locked' => false,
  542. 'hidden' => false
  543. );
  544. // root attributes
  545. $this->attributes[] = array(
  546. 'pattern' => '~^'.preg_quote(DIRECTORY_SEPARATOR).'$~',
  547. 'locked' => true,
  548. 'hidden' => false
  549. );
  550. // set files attributes
  551. if (!empty($this->options['attributes']) && is_array($this->options['attributes'])) {
  552. foreach ($this->options['attributes'] as $a) {
  553. // attributes must contain pattern and at least one rule
  554. if (!empty($a['pattern']) || count($a) > 1) {
  555. $this->attributes[] = $a;
  556. }
  557. }
  558. }
  559. if (!empty($this->options['accessControl']) && is_callable($this->options['accessControl'])) {
  560. $this->access = $this->options['accessControl'];
  561. }
  562. $this->today = mktime(0,0,0, date('m'), date('d'), date('Y'));
  563. $this->yesterday = $this->today-86400;
  564. // debug($this->attributes);
  565. if (!$this->init()) {
  566. return false;
  567. }
  568. // check some options is arrays
  569. $this->uploadAllow = isset($this->options['uploadAllow']) && is_array($this->options['uploadAllow'])
  570. ? $this->options['uploadAllow']
  571. : array();
  572. $this->uploadDeny = isset($this->options['uploadDeny']) && is_array($this->options['uploadDeny'])
  573. ? $this->options['uploadDeny']
  574. : array();
  575. if (is_string($this->options['uploadOrder'])) { // telephat_mode on, compatibility with 1.x
  576. $parts = explode(',', isset($this->options['uploadOrder']) ? $this->options['uploadOrder'] : 'deny,allow');
  577. $this->uploadOrder = array(trim($parts[0]), trim($parts[1]));
  578. } else { // telephat_mode off
  579. $this->uploadOrder = $this->options['uploadOrder'];
  580. }
  581. if (!empty($this->options['uploadMaxSize'])) {
  582. $size = ''.$this->options['uploadMaxSize'];
  583. $unit = strtolower(substr($size, strlen($size) - 1));
  584. $n = 1;
  585. switch ($unit) {
  586. case 'k':
  587. $n = 1024;
  588. break;
  589. case 'm':
  590. $n = 1048576;
  591. break;
  592. case 'g':
  593. $n = 1073741824;
  594. }
  595. $this->uploadMaxSize = intval($size)*$n;
  596. }
  597. $this->disabled = isset($this->options['disabled']) && is_array($this->options['disabled'])
  598. ? $this->options['disabled']
  599. : array();
  600. $this->cryptLib = $this->options['cryptLib'];
  601. $this->mimeDetect = $this->options['mimeDetect'];
  602. // find available mimetype detect method
  603. $type = strtolower($this->options['mimeDetect']);
  604. $type = preg_match('/^(finfo|mime_content_type|internal|auto)$/i', $type) ? $type : 'auto';
  605. $regexp = '/text\/x\-(php|c\+\+)/';
  606. if (($type == 'finfo' || $type == 'auto')
  607. && class_exists('finfo')) {
  608. $tmpFileInfo = @explode(';', @finfo_file(finfo_open(FILEINFO_MIME), __FILE__));
  609. } else {
  610. $tmpFileInfo = false;
  611. }
  612. if ($tmpFileInfo && preg_match($regexp, array_shift($tmpFileInfo))) {
  613. $type = 'finfo';
  614. $this->finfo = finfo_open(FILEINFO_MIME);
  615. } elseif (($type == 'mime_content_type' || $type == 'auto')
  616. && function_exists('mime_content_type')
  617. && preg_match($regexp, array_shift(explode(';', mime_content_type(__FILE__))))) {
  618. $type = 'mime_content_type';
  619. } else {
  620. $type = 'internal';
  621. }
  622. $this->mimeDetect = $type;
  623. // load mimes from external file for mimeDetect == 'internal'
  624. // based on Alexey Sukhotin idea and patch: http://elrte.org/redmine/issues/163
  625. // file must be in file directory or in parent one
  626. if ($this->mimeDetect == 'internal' && !self::$mimetypesLoaded) {
  627. self::$mimetypesLoaded = true;
  628. $this->mimeDetect = 'internal';
  629. $file = false;
  630. if (!empty($this->options['mimefile']) && file_exists($this->options['mimefile'])) {
  631. $file = $this->options['mimefile'];
  632. } elseif (file_exists(dirname(__FILE__).DIRECTORY_SEPARATOR.'mime.types')) {
  633. $file = dirname(__FILE__).DIRECTORY_SEPARATOR.'mime.types';
  634. } elseif (file_exists(dirname(dirname(__FILE__)).DIRECTORY_SEPARATOR.'mime.types')) {
  635. $file = dirname(dirname(__FILE__)).DIRECTORY_SEPARATOR.'mime.types';
  636. }
  637. if ($file && file_exists($file)) {
  638. $mimecf = file($file);
  639. foreach ($mimecf as $line_num => $line) {
  640. if (!preg_match('/^\s*#/', $line)) {
  641. $mime = preg_split('/\s+/', $line, -1, PREG_SPLIT_NO_EMPTY);
  642. for ($i = 1, $size = count($mime); $i < $size ; $i++) {
  643. if (!isset(self::$mimetypes[$mime[$i]])) {
  644. self::$mimetypes[$mime[$i]] = $mime[0];
  645. }
  646. }
  647. }
  648. }
  649. }
  650. }
  651. $this->rootName = empty($this->options['alias']) ? $this->_basename($this->root) : $this->options['alias'];
  652. $root = $this->stat($this->root);
  653. if (!$root) {
  654. return $this->setError('Root folder does not exists.');
  655. }
  656. if (!$root['read'] && !$root['write']) {
  657. return $this->setError('Root folder has not read and write permissions.');
  658. }
  659. // debug($root);
  660. if ($root['read']) {
  661. // check startPath - path to open by default instead of root
  662. if ($this->options['startPath']) {
  663. $start = $this->stat($this->options['startPath']);
  664. if (!empty($start)
  665. && $start['mime'] == 'directory'
  666. && $start['read']
  667. && empty($start['hidden'])
  668. && $this->_inpath($this->options['startPath'], $this->root)) {
  669. $this->startPath = $this->options['startPath'];
  670. if (substr($this->startPath, -1, 1) == $this->options['separator']) {
  671. $this->startPath = substr($this->startPath, 0, -1);
  672. }
  673. }
  674. }
  675. } else {
  676. $this->options['URL'] = '';
  677. $this->options['tmbURL'] = '';
  678. $this->options['tmbPath'] = '';
  679. // read only volume
  680. array_unshift($this->attributes, array(
  681. 'pattern' => '/.*/',
  682. 'read' => false
  683. ));
  684. }
  685. $this->treeDeep = $this->options['treeDeep'] > 0 ? (int)$this->options['treeDeep'] : 1;
  686. $this->tmbSize = $this->options['tmbSize'] > 0 ? (int)$this->options['tmbSize'] : 48;
  687. $this->URL = $this->options['URL'];
  688. if ($this->URL && preg_match("|[^/?&=]$|", $this->URL)) {
  689. $this->URL .= '/';
  690. }
  691. $this->tmbURL = !empty($this->options['tmbURL']) ? $this->options['tmbURL'] : '';
  692. if ($this->tmbURL && preg_match("|[^/?&=]$|", $this->tmbURL)) {
  693. $this->tmbURL .= '/';
  694. }
  695. $this->nameValidator = is_string($this->options['acceptedName']) && !empty($this->options['acceptedName'])
  696. ? $this->options['acceptedName']
  697. : '';
  698. $this->_checkArchivers();
  699. // manual control archive types to create
  700. if (!empty($this->options['archiveMimes']) && is_array($this->options['archiveMimes'])) {
  701. foreach ($this->archivers['create'] as $mime => $v) {
  702. if (!in_array($mime, $this->options['archiveMimes'])) {
  703. unset($this->archivers['create'][$mime]);
  704. }
  705. }
  706. }
  707. // manualy add archivers
  708. if (!empty($this->options['archivers']['create']) && is_array($this->options['archivers']['create'])) {
  709. foreach ($this->options['archivers']['create'] as $mime => $conf) {
  710. if (strpos($mime, 'application/') === 0
  711. && !empty($conf['cmd'])
  712. && isset($conf['argc'])
  713. && !empty($conf['ext'])
  714. && !isset($this->archivers['create'][$mime])) {
  715. $this->archivers['create'][$mime] = $conf;
  716. }
  717. }
  718. }
  719. if (!empty($this->options['archivers']['extract']) && is_array($this->options['archivers']['extract'])) {
  720. foreach ($this->options['archivers']['extract'] as $mime => $conf) {
  721. if (substr($mime, 'application/') === 0
  722. && !empty($cons['cmd'])
  723. && isset($conf['argc'])
  724. && !empty($conf['ext'])
  725. && !isset($this->archivers['extract'][$mime])) {
  726. $this->archivers['extract'][$mime] = $conf;
  727. }
  728. }
  729. }
  730. $this->configure();
  731. // echo $this->uploadMaxSize;
  732. // echo $this->options['uploadMaxSize'];
  733. return $this->mounted = true;
  734. }
  735. /**
  736. * Some "unmount" stuffs - may be required by virtual fs
  737. *
  738. * @return void
  739. * @author Dmitry (dio) Levashov
  740. **/
  741. public function umount() {
  742. }
  743. /**
  744. * Return error message from last failed action
  745. *
  746. * @return array
  747. * @author Dmitry (dio) Levashov
  748. **/
  749. public function error() {
  750. return $this->error;
  751. }
  752. /**
  753. * Set mimetypes allowed to display to client
  754. *
  755. * @param array $mimes
  756. * @return void
  757. * @author Dmitry (dio) Levashov
  758. **/
  759. public function setMimesFilter($mimes) {
  760. if (is_array($mimes)) {
  761. $this->onlyMimes = $mimes;
  762. }
  763. }
  764. /**
  765. * Return root folder hash
  766. *
  767. * @return string
  768. * @author Dmitry (dio) Levashov
  769. **/
  770. public function root() {
  771. return $this->encode($this->root);
  772. }
  773. /**
  774. * Return root or startPath hash
  775. *
  776. * @return string
  777. * @author Dmitry (dio) Levashov
  778. **/
  779. public function defaultPath() {
  780. return $this->encode($this->startPath ? $this->startPath : $this->root);
  781. }
  782. /**
  783. * Return volume options required by client:
  784. *
  785. * @return array
  786. * @author Dmitry (dio) Levashov
  787. **/
  788. public function options($hash) {
  789. return array(
  790. 'path' => $this->_path($this->decode($hash)),
  791. 'url' => $this->URL,
  792. 'tmbUrl' => $this->tmbURL,
  793. 'disabled' => $this->disabled,
  794. 'separator' => $this->separator,
  795. 'copyOverwrite' => intval($this->options['copyOverwrite']),
  796. 'archivers' => array(
  797. // 'create' => array_keys($this->archivers['create']),
  798. // 'extract' => array_keys($this->archivers['extract']),
  799. 'create' => is_array($this->archivers['create']) ? array_keys($this->archivers['create']) : array(),
  800. 'extract' => is_array($this->archivers['extract']) ? array_keys($this->archivers['extract']) : array()
  801. )
  802. );
  803. }
  804. /**
  805. * Return true if command disabled in options
  806. *
  807. * @param string $cmd command name
  808. * @return bool
  809. * @author Dmitry (dio) Levashov
  810. **/
  811. public function commandDisabled($cmd) {
  812. return in_array($cmd, $this->disabled);
  813. }
  814. /**
  815. * Return true if mime is required mimes list
  816. *
  817. * @param string $mime mime type to check
  818. * @param array $mimes allowed mime types list or not set to use client mimes list
  819. * @param bool|null $empty what to return on empty list
  820. * @return bool|null
  821. * @author Dmitry (dio) Levashov
  822. * @author Troex Nevelin
  823. **/
  824. public function mimeAccepted($mime, $mimes = array(), $empty = true) {
  825. $mimes = !empty($mimes) ? $mimes : $this->onlyMimes;
  826. if (empty($mimes)) {
  827. return $empty;
  828. }
  829. return $mime == 'directory'
  830. || in_array('all', $mimes)
  831. || in_array('All', $mimes)
  832. || in_array($mime, $mimes)
  833. || in_array(substr($mime, 0, strpos($mime, '/')), $mimes);
  834. }
  835. /**
  836. * Return true if voume is readable.
  837. *
  838. * @return bool
  839. * @author Dmitry (dio) Levashov
  840. **/
  841. public function isReadable() {
  842. $stat = $this->stat($this->root);
  843. return $stat['read'];
  844. }
  845. /**
  846. * Return true if copy from this volume allowed
  847. *
  848. * @return bool
  849. * @author Dmitry (dio) Levashov
  850. **/
  851. public function copyFromAllowed() {
  852. return !!$this->options['copyFrom'];
  853. }
  854. /**
  855. * Return file path related to root
  856. *
  857. * @param string $hash file hash
  858. * @return string
  859. * @author Dmitry (dio) Levashov
  860. **/
  861. public function path($hash) {
  862. return $this->_path($this->decode($hash));
  863. }
  864. /**
  865. * Return file real path if file exists
  866. *
  867. * @param string $hash file hash
  868. * @return string
  869. * @author Dmitry (dio) Levashov
  870. **/
  871. public function realpath($hash) {
  872. $path = $this->decode($hash);
  873. return $this->stat($path) ? $path : false;
  874. }
  875. /**
  876. * Return list of moved/overwrited files
  877. *
  878. * @return array
  879. * @author Dmitry (dio) Levashov
  880. **/
  881. public function removed() {
  882. return $this->removed;
  883. }
  884. /**
  885. * Clean removed files list
  886. *
  887. * @return void
  888. * @author Dmitry (dio) Levashov
  889. **/
  890. public function resetRemoved() {
  891. $this->removed = array();
  892. }
  893. /**
  894. * Return file/dir hash or first founded child hash with required attr == $val
  895. *
  896. * @param string $hash file hash
  897. * @param string $attr attribute name
  898. * @param bool $val attribute value
  899. * @return string|false
  900. * @author Dmitry (dio) Levashov
  901. **/
  902. public function closest($hash, $attr, $val) {
  903. return ($path = $this->closestByAttr($this->decode($hash), $attr, $val)) ? $this->encode($path) : false;
  904. }
  905. /**
  906. * Return file info or false on error
  907. *
  908. * @param string $hash file hash
  909. * @param bool $realpath add realpath field to file info
  910. * @return array|false
  911. * @author Dmitry (dio) Levashov
  912. **/
  913. public function file($hash) {
  914. $path = $this->decode($hash);
  915. return ($file = $this->stat($path)) ? $file : $this->setError(elFinder::ERROR_FILE_NOT_FOUND);
  916. if (($file = $this->stat($path)) != false) {
  917. if ($realpath) {
  918. $file['realpath'] = $path;
  919. }
  920. return $file;
  921. }
  922. return $this->setError(elFinder::ERROR_FILE_NOT_FOUND);
  923. }
  924. /**
  925. * Return folder info
  926. *
  927. * @param string $hash folder hash
  928. * @param bool $hidden return hidden file info
  929. * @return array|false
  930. * @author Dmitry (dio) Levashov
  931. **/
  932. public function dir($hash, $resolveLink=false) {
  933. if (($dir = $this->file($hash)) == false) {
  934. return $this->setError(elFinder::ERROR_DIR_NOT_FOUND);
  935. }
  936. if ($resolveLink && !empty($dir['thash'])) {
  937. $dir = $this->file($dir['thash']);
  938. }
  939. return $dir && $dir['mime'] == 'directory' && empty($dir['hidden'])
  940. ? $dir
  941. : $this->setError(elFinder::ERROR_NOT_DIR);
  942. }
  943. /**
  944. * Return directory content or false on error
  945. *
  946. * @param string $hash file hash
  947. * @return array|false
  948. * @author Dmitry (dio) Levashov
  949. **/
  950. public function scandir($hash) {
  951. if (($dir = $this->dir($hash)) == false) {
  952. return false;
  953. }
  954. return $dir['read']
  955. ? $this->getScandir($this->decode($hash))
  956. : $this->setError(elFinder::ERROR_PERM_DENIED);
  957. }
  958. /**
  959. * Return dir files names list
  960. *
  961. * @param string $hash file hash
  962. * @return array
  963. * @author Dmitry (dio) Levashov
  964. **/
  965. public function ls($hash) {
  966. if (($dir = $this->dir($hash)) == false || !$dir['read']) {
  967. return false;
  968. }
  969. $list = array();
  970. $path = $this->decode($hash);
  971. foreach ($this->getScandir($path) as $stat) {
  972. if (empty($stat['hidden']) && $this->mimeAccepted($stat['mime'])) {
  973. $list[] = $stat['name'];
  974. }
  975. }
  976. return $list;
  977. }
  978. /**
  979. * Return subfolders for required folder or false on error
  980. *
  981. * @param string $hash folder hash or empty string to get tree from root folder
  982. * @param int $deep subdir deep
  983. * @param string $exclude dir hash which subfolders must be exluded from result, required to not get stat twice on cwd subfolders
  984. * @return array|false
  985. * @author Dmitry (dio) Levashov
  986. **/
  987. public function tree($hash='', $deep=0, $exclude='') {
  988. $path = $hash ? $this->decode($hash) : $this->root;
  989. if (($dir = $this->stat($path)) == false || $dir['mime'] != 'directory') {
  990. return false;
  991. }
  992. $dirs = $this->gettree($path, $deep > 0 ? $deep -1 : $this->treeDeep-1, $exclude ? $this->decode($exclude) : null);
  993. array_unshift($dirs, $dir);
  994. return $dirs;
  995. }
  996. /**
  997. * Return part of dirs tree from required dir up to root dir
  998. *
  999. * @param string $hash directory hash
  1000. * @return array
  1001. * @author Dmitry (dio) Levashov
  1002. **/
  1003. public function parents($hash) {
  1004. if (($current = $this->dir($hash)) == false) {
  1005. return false;
  1006. }
  1007. $path = $this->decode($hash);
  1008. $tree = array();
  1009. while ($path && $path != $this->root) {
  1010. $path = $this->_dirname($path);
  1011. $stat = $this->stat($path);
  1012. if (!empty($stat['hidden']) || !$stat['read']) {
  1013. return false;
  1014. }
  1015. array_unshift($tree, $stat);
  1016. if ($path != $this->root) {
  1017. foreach ($this->gettree($path, 0) as $dir) {
  1018. if (!in_array($dir, $tree)) {
  1019. $tree[] = $dir;
  1020. }
  1021. }
  1022. }
  1023. }
  1024. return $tree ? $tree : array($current);
  1025. }
  1026. /**
  1027. * Create thumbnail for required file and return its name of false on failed
  1028. *
  1029. * @return string|false
  1030. * @author Dmitry (dio) Levashov
  1031. **/
  1032. public function tmb($hash) {
  1033. $path = $this->decode($hash);
  1034. $stat = $this->stat($path);
  1035. if (isset($stat['tmb'])) {
  1036. return $stat['tmb'] == "1" ? $this->createTmb($path, $stat) : $stat['tmb'];
  1037. }
  1038. return false;
  1039. }
  1040. /**
  1041. * Return file size / total directory size
  1042. *
  1043. * @param string file hash
  1044. * @return int
  1045. * @author Dmitry (dio) Levashov
  1046. **/
  1047. public function size($hash) {
  1048. return $this->countSize($this->decode($hash));
  1049. }
  1050. /**
  1051. * Open file for reading and return file pointer
  1052. *
  1053. * @param string file hash
  1054. * @return Resource
  1055. * @author Dmitry (dio) Levashov
  1056. **/
  1057. public function open($hash) {
  1058. if (($file = $this->file($hash)) == false
  1059. || $file['mime'] == 'directory') {
  1060. return false;
  1061. }
  1062. return $this->_fopen($this->decode($hash), 'rb');
  1063. }
  1064. /**
  1065. * Close file pointer
  1066. *
  1067. * @param Resource $fp file pointer
  1068. * @param string $hash file hash
  1069. * @return void
  1070. * @author Dmitry (dio) Levashov
  1071. **/
  1072. public function close($fp, $hash) {
  1073. $this->_fclose($fp, $this->decode($hash));
  1074. }
  1075. /**
  1076. * Create directory and return dir info
  1077. *
  1078. * @param string $dst destination directory
  1079. * @param string $name directory name
  1080. * @return array|false
  1081. * @author Dmitry (dio) Levashov
  1082. **/
  1083. public function mkdir($dst, $name) {
  1084. if ($this->commandDisabled('mkdir')) {
  1085. return $this->setError(elFinder::ERROR_PERM_DENIED);
  1086. }
  1087. if (!$this->nameAccepted($name)) {
  1088. return $this->setError(elFinder::ERROR_INVALID_NAME);
  1089. }
  1090. if (($dir = $this->dir($dst)) == false) {
  1091. return $this->setError(elFinder::ERROR_TRGDIR_NOT_FOUND, '#'.$dst);
  1092. }
  1093. if (!$dir['write']) {
  1094. return $this->setError(elFinder::ERROR_PERM_DENIED);
  1095. }
  1096. $path = $this->decode($dst);
  1097. $dst = $this->_joinPath($path, $name);
  1098. $stat = $this->stat($dst);
  1099. if (!empty($stat)) {
  1100. return $this->setError(elFinder::ERROR_EXISTS, $name);
  1101. }
  1102. $this->clearcache();
  1103. return ($path = $this->_mkdir($path, $name)) ? $this->stat($path) : false;
  1104. }
  1105. /**
  1106. * Create empty file and return its info
  1107. *
  1108. * @param string $dst destination directory
  1109. * @param string $name file name
  1110. * @return array|false
  1111. * @author Dmitry (dio) Levashov
  1112. **/
  1113. public function mkfile($dst, $name) {
  1114. if ($this->commandDisabled('mkfile')) {
  1115. return $this->setError(elFinder::ERROR_PERM_DENIED);
  1116. }
  1117. if (!$this->nameAccepted($name)) {
  1118. return $this->setError(elFinder::ERROR_INVALID_NAME);
  1119. }
  1120. if (($dir = $this->dir($dst)) == false) {
  1121. return $this->setError(elFinder::ERROR_TRGDIR_NOT_FOUND, '#'.$dst);
  1122. }
  1123. $path = $this->decode($dst);
  1124. if (!$dir['write'] || !$this->allowCreate($path, $name)) {
  1125. return $this->setError(elFinder::ERROR_PERM_DENIED);
  1126. }
  1127. if ($this->stat($this->_joinPath($path, $name))) {
  1128. return $this->setError(elFinder::ERROR_EXISTS, $name);
  1129. }
  1130. $this->clearcache();
  1131. return ($path = $this->_mkfile($path, $name)) ? $this->stat($path) : false;
  1132. }
  1133. /**
  1134. * Rename file and return file info
  1135. *
  1136. * @param string $hash file hash
  1137. * @param string $name new file name
  1138. * @return array|false
  1139. * @author Dmitry (dio) Levashov
  1140. **/
  1141. public function rename($hash, $name) {
  1142. if ($this->commandDisabled('rename')) {
  1143. return $this->setError(elFinder::ERROR_PERM_DENIED);
  1144. }
  1145. if (!$this->nameAccepted($name)) {
  1146. return $this->setError(elFinder::ERROR_INVALID_NAME, $name);
  1147. }
  1148. if (!($file = $this->file($hash))) {
  1149. return $this->setError(elFinder::ERROR_FILE_NOT_FOUND);
  1150. }
  1151. if ($name == $file['name']) {
  1152. return $file;
  1153. }
  1154. if (!empty($file['locked'])) {
  1155. return $this->setError(elFinder::ERROR_LOCKED, $file['name']);
  1156. }
  1157. $path = $this->decode($hash);
  1158. $dir = $this->_dirname($path);
  1159. $stat = $this->stat($this->_joinPath($dir, $name));
  1160. if ($stat) {
  1161. return $this->setError(elFinder::ERROR_EXISTS, $name);
  1162. }
  1163. if (!$this->allowCreate($dir, $name)) {
  1164. return $this->setError(elFinder::ERROR_PERM_DENIED);
  1165. }
  1166. $this->rmTmb($file); // remove old name tmbs, we cannot do this after dir move
  1167. if (($path = $this->_move($path, $dir, $name))) {
  1168. $this->clearcache();
  1169. return $this->stat($path);
  1170. }
  1171. return false;
  1172. }
  1173. /**
  1174. * Create file copy with suffix "copy number" and return its info
  1175. *
  1176. * @param string $hash file hash
  1177. * @param string $suffix suffix to add to file name
  1178. * @return array|false
  1179. * @author Dmitry (dio) Levashov
  1180. **/
  1181. public function duplicate($hash, $suffix='copy') {
  1182. if ($this->commandDisabled('duplicate')) {
  1183. return $this->setError(elFinder::ERROR_COPY, '#'.$hash, elFinder::ERROR_PERM_DENIED);
  1184. }
  1185. if (($file = $this->file($hash)) == false) {
  1186. return $this->setError(elFinder::ERROR_COPY, elFinder::ERROR_FILE_NOT_FOUND);
  1187. }
  1188. $path = $this->decode($hash);
  1189. $dir = $this->_dirname($path);
  1190. $name = $this->uniqueName($dir, $this->_basename($path), ' '.$suffix.' ');
  1191. if (!$this->allowCreate($dir, $name)) {
  1192. return $this->setError(elFinder::ERROR_PERM_DENIED);
  1193. }
  1194. return ($path = $this->copy($path, $dir, $name)) == false
  1195. ? false
  1196. : $this->stat($path);
  1197. }
  1198. /**
  1199. * Save uploaded file.
  1200. * On success return array with new file stat and with removed file hash (if existed file was replaced)
  1201. *
  1202. * @param Resource $fp file pointer
  1203. * @param string $dst destination folder hash
  1204. * @param string $src file name
  1205. * @param string $tmpname file tmp name - required to detect mime type
  1206. * @return array|false
  1207. * @author Dmitry (dio) Levashov
  1208. **/
  1209. public function upload($fp, $dst, $name, $tmpname) {
  1210. if ($this->commandDisabled('upload')) {
  1211. return $this->setError(elFinder::ERROR_PERM_DENIED);
  1212. }
  1213. if (($dir = $this->dir($dst)) == false) {
  1214. return $this->setError(elFinder::ERROR_TRGDIR_NOT_FOUND, '#'.$dst);
  1215. }
  1216. if (!$dir['write']) {
  1217. return $this->setError(elFinder::ERROR_PERM_DENIED);
  1218. }
  1219. if (!$this->nameAccepted($name)) {
  1220. return $this->setError(elFinder::ERROR_INVALID_NAME);
  1221. }
  1222. $mime = $this->mimetype($this->mimeDetect == 'internal' ? $name : $tmpname, $name);
  1223. if ($mime == 'unknown' && $this->mimeDetect == 'internal') {
  1224. $mime = elFinderVolumeDriver::mimetypeInternalDetect($name);
  1225. }
  1226. // logic based on http://httpd.apache.org/docs/2.2/mod/mod_authz_host.html#order
  1227. $allow = $this->mimeAccepted($mime, $this->uploadAllow, null);
  1228. $deny = $this->mimeAccepted($mime, $this->uploadDeny, null);
  1229. $upload = true; // default to allow
  1230. if (strtolower($this->uploadOrder[0]) == 'allow') { // array('allow', 'deny'), default is to 'deny'
  1231. $upload = false; // default is deny
  1232. if (!$deny && ($allow === true)) { // match only allow
  1233. $upload = true;
  1234. }// else (both match | no match | match only deny) { deny }
  1235. } else { // array('deny', 'allow'), default is to 'allow' - this is the default rule
  1236. $upload = true; // default is allow
  1237. if (($deny === true) && !$allow) { // match only deny
  1238. $upload = false;
  1239. } // else (both match | no match | match only allow) { allow }
  1240. }
  1241. if (!$upload) {
  1242. return $this->setError(elFinder::ERROR_UPLOAD_FILE_MIME);
  1243. }
  1244. if ($this->uploadMaxSize > 0 && filesize($tmpname) > $this->uploadMaxSize) {
  1245. return $this->setError(elFinder::ERROR_UPLOAD_FILE_SIZE);
  1246. }
  1247. $dstpath = $this->decode($dst);
  1248. $test = $this->_joinPath($dstpath, $name);
  1249. $file = $this->stat($test);
  1250. $this->clearcache();
  1251. if ($file) { // file exists
  1252. if ($this->options['uploadOverwrite']) {
  1253. if (!$file['write']) {
  1254. return $this->setError(elFinder::ERROR_PERM_DENIED);
  1255. } elseif ($file['mime'] == 'directory') {
  1256. return $this->setError(elFinder::ERROR_NOT_REPLACE, $name);
  1257. }
  1258. $this->remove($test);
  1259. } else {
  1260. $name = $this->uniqueName($dstpath, $name, '-', false);
  1261. }
  1262. }
  1263. $stat = array(
  1264. 'mime' => $mime,
  1265. 'width' => 0,
  1266. 'height' => 0,
  1267. 'size' => filesize($tmpname));
  1268. // $w = $h = 0;
  1269. if (strpos($mime, 'image') === 0 && ($s = getimagesize($tmpname))) {
  1270. $stat['width'] = $s[0];
  1271. $stat['height'] = $s[1];
  1272. }
  1273. // $this->clearcache();
  1274. if (($path = $this->_save($fp, $dstpath, $name, $stat)) == false) {
  1275. return false;
  1276. }
  1277. return $this->stat($path);
  1278. }
  1279. /**
  1280. * Paste files
  1281. *
  1282. * @param Object $volume source volume
  1283. * @param string $source file hash
  1284. * @param string $dst destination dir hash
  1285. * @param bool $rmSrc remove source after copy?
  1286. * @return array|false
  1287. * @author Dmitry (dio) Levashov
  1288. **/
  1289. public function paste($volume, $src, $dst, $rmSrc = false) {
  1290. $err = $rmSrc ? elFinder::ERROR_MOVE : elFinder::ERROR_COPY;
  1291. if ($this->commandDisabled('paste')) {
  1292. return $this->setError($err, '#'.$src, elFinder::ERROR_PERM_DENIED);
  1293. }
  1294. if (($file = $volume->file($src, $rmSrc)) == false) {
  1295. return $this->setError($err, '#'.$src, elFinder::ERROR_FILE_NOT_FOUND);
  1296. }
  1297. $name = $file['name'];
  1298. $errpath = $volume->path($src);
  1299. if (($dir = $this->dir($dst)) == false) {
  1300. return $this->setError($err, $errpath, elFinder::ERROR_TRGDIR_NOT_FOUND, '#'.$dst);
  1301. }
  1302. if (!$dir['write'] || !$file['read']) {
  1303. return $this->setError($err, $errpath, elFinder::ERROR_PERM_DENIED);
  1304. }
  1305. $destination = $this->decode($dst);
  1306. if (($test = $volume->closest($src, $rmSrc ? 'locked' : 'read', $rmSrc))) {
  1307. return $rmSrc
  1308. ? $this->setError($err, $errpath, elFinder::ERROR_LOCKED, $volume->path($test))
  1309. : $this->setError($err, $errpath, elFinder::ERROR_PERM_DENIED);
  1310. }
  1311. $test = $this->_joinPath($destination, $name);
  1312. $stat = $this->stat($test);
  1313. $this->clearcache();
  1314. if ($stat) {
  1315. if ($this->options['copyOverwrite']) {
  1316. // do not replace file with dir or dir with file
  1317. if (!$this->isSameType($file['mime'], $stat['mime'])) {
  1318. return $this->setError(elFinder::ERROR_NOT_REPLACE, $this->_path($test));
  1319. }
  1320. // existed file is not writable
  1321. if (!$stat['write']) {
  1322. return $this->setError($err, $errpath, elFinder::ERROR_PERM_DENIED);
  1323. }
  1324. // existed file locked or has locked child
  1325. if (($locked = $this->closestByAttr($test, 'locked', true))) {
  1326. return $this->setError(elFinder::ERROR_LOCKED, $this->_path($locked));
  1327. }
  1328. // target is entity file of alias
  1329. if ($volume == $this && ($test == @$file['target'] || $test == $this->decode($src))) {
  1330. return $this->setError(elFinder::ERROR_REPLACE, $errpath);
  1331. }
  1332. // remove existed file
  1333. if (!$this->remove($test)) {
  1334. return $this->setError(elFinder::ERROR_REPLACE, $this->_path($test));
  1335. }
  1336. } else {
  1337. $name = $this->uniqueName($destination, $name, ' ', false);
  1338. }
  1339. }
  1340. // copy/move inside current volume
  1341. if ($volume == $this) {
  1342. $source = $this->decode($src);
  1343. // do not copy into itself
  1344. if ($this->_inpath($destination, $source)) {
  1345. return $this->setError(elFinder::ERROR_COPY_INTO_ITSELF, $errpath);
  1346. }
  1347. $method = $rmSrc ? 'move' : 'copy';
  1348. return ($path = $this->$method($source, $destination, $name)) ? $this->stat($path) : false;
  1349. }
  1350. // copy/move from another volume
  1351. if (!$this->options['copyTo'] || !$volume->copyFromAllowed()) {
  1352. return $this->setError(elFinder::ERROR_COPY, $errpath, elFinder::ERROR_PERM_DENIED);
  1353. }
  1354. if (($path = $this->copyFrom($volume, $src, $destination, $name)) == false) {
  1355. return false;
  1356. }
  1357. if ($rmSrc) {
  1358. if ($volume->rm($src)) {
  1359. $this->removed[] = $file;
  1360. } else {
  1361. return $this->setError(elFinder::ERROR_MOVE, $errpath, elFinder::ERROR_RM_SRC);
  1362. }
  1363. }
  1364. return $this->stat($path);
  1365. }
  1366. /**
  1367. * Return file contents
  1368. *
  1369. * @param string $hash file hash
  1370. * @return string|false
  1371. * @author Dmitry (dio) Levashov
  1372. **/
  1373. public function getContents($hash) {
  1374. $file = $this->file($hash);
  1375. if (!$file) {
  1376. return $this->setError(elFinder::ERROR_FILE_NOT_FOUND);
  1377. }
  1378. if ($file['mime'] == 'directory') {
  1379. return $this->setError(elFinder::ERROR_NOT_FILE);
  1380. }
  1381. if (!$file['read']) {
  1382. return $this->setError(elFinder::ERROR_PERM_DENIED);
  1383. }
  1384. return $this->_getContents($this->decode($hash));
  1385. }
  1386. /**
  1387. * Put content in text file and return file info.
  1388. *
  1389. * @param string $hash file hash
  1390. * @param string $content new file content
  1391. * @return array
  1392. * @author Dmitry (dio) Levashov
  1393. **/
  1394. public function putContents($hash, $content) {
  1395. if ($this->commandDisabled('edit')) {
  1396. return $this->setError(elFinder::ERROR_PERM_DENIED);
  1397. }
  1398. $path = $this->decode($hash);
  1399. if (!($file = $this->file($hash))) {
  1400. return $this->setError(elFinder::ERROR_FILE_NOT_FOUND);
  1401. }
  1402. if (!$file['write']) {
  1403. return $this->setError(elFinder::ERROR_PERM_DENIED);
  1404. }
  1405. $this->clearcache();
  1406. return $this->_filePutContents($path, $content) ? $this->stat($path) : false;
  1407. }
  1408. /**
  1409. * Extract files from archive
  1410. *
  1411. * @param string $hash archive hash
  1412. * @return array|bool
  1413. * @author Dmitry (dio) Levashov,
  1414. * @author Alexey Sukhotin
  1415. **/
  1416. public function extract($hash) {
  1417. if ($this->commandDisabled('extract')) {
  1418. return $this->setError(elFinder::ERROR_PERM_DENIED);
  1419. }
  1420. if (($file = $this->file($hash)) == false) {
  1421. return $this->setError(elFinder::ERROR_FILE_NOT_FOUND);
  1422. }
  1423. $archiver = isset($this->archivers['extract'][$file['mime']])
  1424. ? $this->archivers['extract'][$file['mime']]
  1425. : false;
  1426. if (!$archiver) {
  1427. return $this->setError(elFinder::ERROR_NOT_ARCHIVE);
  1428. }
  1429. $path = $this->decode($hash);
  1430. $parent = $this->stat($this->_dirname($path));
  1431. if (!$file['read'] || !$parent['write']) {
  1432. return $this->setError(elFinder::ERROR_PERM_DENIED);
  1433. }
  1434. $this->clearcache();
  1435. return ($path = $this->_extract($path, $archiver)) ? $this->stat($path) : false;
  1436. }
  1437. /**
  1438. * Add files to archive
  1439. *
  1440. * @return void
  1441. **/
  1442. public function archive($hashes, $mime) {
  1443. if ($this->commandDisabled('archive')) {
  1444. return $this->setError(elFinder::ERROR_PERM_DENIED);
  1445. }
  1446. $archiver = isset($this->archivers['create'][$mime])
  1447. ? $this->archivers['create'][$mime]
  1448. : false;
  1449. if (!$archiver) {
  1450. return $this->setError(elFinder::ERROR_ARCHIVE_TYPE);
  1451. }
  1452. $files = array();
  1453. foreach ($hashes as $hash) {
  1454. if (($file = $this->file($hash)) == false) {
  1455. return $this->error(elFinder::ERROR_FILE_NOT_FOUND, '#'+$hash);
  1456. }
  1457. if (!$file['read']) {
  1458. return $this->error(elFinder::ERROR_PERM_DENIED);
  1459. }
  1460. $path = $this->decode($hash);
  1461. if (!isset($dir)) {
  1462. $dir = $this->_dirname($path);
  1463. $stat = $this->stat($dir);
  1464. if (!$stat['write']) {
  1465. return $this->error(elFinder::ERROR_PERM_DENIED);
  1466. }
  1467. }
  1468. $files[] = $this->_basename($path);
  1469. }
  1470. $name = (count($files) == 1 ? $files[0] : 'Archive').'.'.$archiver['ext'];
  1471. $name = $this->uniqueName($dir, $name, '');
  1472. $this->clearcache();
  1473. return ($path = $this->_archive($dir, $files, $name, $archiver)) ? $this->stat($path) : false;
  1474. }
  1475. /**
  1476. * Resize image
  1477. *
  1478. * @param string $hash image file
  1479. * @param int $width new width
  1480. * @param int $height new height
  1481. * @param int $x X start poistion for crop
  1482. * @param int $y Y start poistion for crop
  1483. * @param string $mode action how to mainpulate image
  1484. * @return array|false
  1485. * @author Dmitry (dio) Levashov
  1486. * @author Alexey Sukhotin
  1487. * @author nao-pon
  1488. * @author Troex Nevelin
  1489. **/
  1490. public function resize($hash, $width, $height, $x, $y, $mode = 'resize', $bg = '', $degree = 0) {
  1491. if ($this->commandDisabled('resize')) {
  1492. return $this->setError(elFinder::ERROR_PERM_DENIED);
  1493. }
  1494. if (($file = $this->file($hash)) == false) {
  1495. return $this->setError(elFinder::ERROR_FILE_NOT_FOUND);
  1496. }
  1497. if (!$file['write'] || !$file['read']) {
  1498. return $this->setError(elFinder::ERROR_PERM_DENIED);
  1499. }
  1500. $path = $this->decode($hash);
  1501. if (!$this->canResize($path, $file)) {
  1502. return $this->setError(elFinder::ERROR_UNSUPPORT_TYPE);
  1503. }
  1504. switch($mode) {
  1505. case 'propresize':
  1506. $result = $this->imgResize($path, $width, $height, true, true);
  1507. break;
  1508. case 'crop':
  1509. $result = $this->imgCrop($path, $width, $height, $x, $y);
  1510. break;
  1511. case 'fitsquare':
  1512. $result = $this->imgSquareFit($path, $width, $height, 'center', 'middle', ($bg ? $bg : $this->options['tmbBgColor']));
  1513. break;
  1514. case 'rotate':
  1515. $result = $this->imgRotate($path, $degree, ($bg ? $bg : $this->options['tmbBgColor']));
  1516. break;
  1517. default:
  1518. $result = $this->imgResize($path, $width, $height, false, true);
  1519. break;
  1520. }
  1521. if ($result) {
  1522. $this->rmTmb($file);
  1523. $this->clearcache();
  1524. return $this->stat($path);
  1525. }
  1526. return false;
  1527. }
  1528. /**
  1529. * Remove file/dir
  1530. *
  1531. * @param string $hash file hash
  1532. * @return bool
  1533. * @author Dmitry (dio) Levashov
  1534. **/
  1535. public function rm($hash) {
  1536. return $this->commandDisabled('rm')
  1537. ? array(elFinder::ERROR_ACCESS_DENIED)
  1538. : $this->remove($this->decode($hash));
  1539. }
  1540. /**
  1541. * Search files
  1542. *
  1543. * @param string $q search string
  1544. * @param array $mimes
  1545. * @return array
  1546. * @author Dmitry (dio) Levashov
  1547. **/
  1548. public function search($q, $mimes) {
  1549. return $this->doSearch($this->root, $q, $mimes);
  1550. }
  1551. /**
  1552. * Return image dimensions
  1553. *
  1554. * @param string $hash file hash
  1555. * @return array
  1556. * @author Dmitry (dio) Levashov
  1557. **/
  1558. public function dimensions($hash) {
  1559. if (($file = $this->file($hash)) == false) {
  1560. return false;
  1561. }
  1562. return $this->_dimensions($this->decode($hash), $file['mime']);
  1563. }
  1564. /**
  1565. * Save error message
  1566. *
  1567. * @param array error
  1568. * @return false
  1569. * @author Dmitry(dio) Levashov
  1570. **/
  1571. protected function setError($error) {
  1572. $this->error = array();
  1573. foreach (func_get_args() as $err) {
  1574. if (is_array($err)) {
  1575. $this->error = array_merge($this->error, $err);
  1576. } else {
  1577. $this->error[] = $err;
  1578. }
  1579. }
  1580. // $this->error = is_array($error) ? $error : func_get_args();
  1581. return false;
  1582. }
  1583. /*********************************************************************/
  1584. /* FS API */
  1585. /*********************************************************************/
  1586. /***************** paths *******************/
  1587. /**
  1588. * Encode path into hash
  1589. *
  1590. * @param string file path
  1591. * @return string
  1592. * @author Dmitry (dio) Levashov
  1593. * @author Troex Nevelin
  1594. **/
  1595. protected function encode($path) {
  1596. if ($path !== '') {
  1597. // cut ROOT from $path for security reason, even if hacker decodes the path he will not know the root
  1598. $p = $this->_relpath($path);
  1599. // if reqesting root dir $path will be empty, then assign '/' as we cannot leave it blank for crypt
  1600. if ($p === '') {
  1601. $p = DIRECTORY_SEPARATOR;
  1602. }
  1603. // TODO crypt path and return hash
  1604. $hash = $this->crypt($p);
  1605. // hash is used as id in HTML that means it must contain vaild chars
  1606. // make base64 html safe and append prefix in begining
  1607. $hash = strtr(base64_encode($hash), '+/=', '-_.');
  1608. // remove dots '.' at the end, before it was '=' in base64
  1609. $hash = rtrim($hash, '.');
  1610. // append volume id to make hash unique
  1611. return $this->id.$hash;
  1612. }
  1613. }
  1614. /**
  1615. * Decode path from hash
  1616. *
  1617. * @param string file hash
  1618. * @return string
  1619. * @author Dmitry (dio) Levashov
  1620. * @author Troex Nevelin
  1621. **/
  1622. protected function decode($hash) {
  1623. if (strpos($hash, $this->id) === 0) {
  1624. // cut volume id after it was prepended in encode
  1625. $h = substr($hash, strlen($this->id));
  1626. // replace HTML safe base64 to normal
  1627. $h = base64_decode(strtr($h, '-_.', '+/='));
  1628. // TODO uncrypt hash and return path
  1629. $path = $this->uncrypt($h);
  1630. // append ROOT to path after it was cut in encode
  1631. return $this->_abspath($path);//$this->root.($path == DIRECTORY_SEPARATOR ? '' : DIRECTORY_SEPARATOR.$path);
  1632. }
  1633. }
  1634. /**
  1635. * Return crypted path
  1636. * Not implemented
  1637. *
  1638. * @param string path
  1639. * @return mixed
  1640. * @author Dmitry (dio) Levashov
  1641. **/
  1642. protected function crypt($path) {
  1643. return $path;
  1644. }
  1645. /**
  1646. * Return uncrypted path
  1647. * Not implemented
  1648. *
  1649. * @param mixed hash
  1650. * @return mixed
  1651. * @author Dmitry (dio) Levashov
  1652. **/
  1653. protected function uncrypt($hash) {
  1654. return $hash;
  1655. }
  1656. /**
  1657. * Validate file name based on $this->options['acceptedName'] regexp
  1658. *
  1659. * @param string $name file name
  1660. * @return bool
  1661. * @author Dmitry (dio) Levashov
  1662. **/
  1663. protected function nameAccepted($name) {
  1664. if ($this->nameValidator) {
  1665. if (function_exists($this->nameValidator)) {
  1666. $f = $this->nameValidator;
  1667. return $f($name);
  1668. }
  1669. return preg_match($this->nameValidator, $name);
  1670. }
  1671. return true;
  1672. }
  1673. /**
  1674. * Return new unique name based on file name and suffix
  1675. *
  1676. * @param string $path file path
  1677. * @param string $suffix suffix append to name
  1678. * @return string
  1679. * @author Dmitry (dio) Levashov
  1680. **/
  1681. public function uniqueName($dir, $name, $suffix = ' copy', $checkNum=true) {
  1682. $ext = '';
  1683. if (preg_match('/\.((tar\.(gz|bz|bz2|z|lzo))|cpio\.gz|ps\.gz|xcf\.(gz|bz2)|[a-z0-9]{1,4})$/i', $name, $m)) {
  1684. $ext = '.'.$m[1];
  1685. $name = substr($name, 0, strlen($name)-strlen($m[0]));
  1686. }
  1687. if ($checkNum && preg_match('/('.$suffix.')(\d*)$/i', $name, $m)) {
  1688. $i = (int)$m[2];
  1689. $name = substr($name, 0, strlen($name)-strlen($m[2]));
  1690. } else {
  1691. $i = 1;
  1692. $name .= $suffix;
  1693. }
  1694. $max = $i+100000;
  1695. while ($i <= $max) {
  1696. $n = $name.($i > 0 ? $i : '').$ext;
  1697. if (!$this->stat($this->_joinPath($dir, $n))) {
  1698. $this->clearcache();
  1699. return $n;
  1700. }
  1701. $i++;
  1702. }
  1703. return $name.md5($dir).$ext;
  1704. }
  1705. /*********************** file stat *********************/
  1706. /**
  1707. * Check file attribute
  1708. *
  1709. * @param string $path file path
  1710. * @param string $name attribute name (read|write|locked|hidden)
  1711. * @param bool $val attribute value returned by file system
  1712. * @return bool
  1713. * @author Dmitry (dio) Levashov
  1714. **/
  1715. protected function attr($path, $name, $val=null) {
  1716. if (!isset($this->defaults[$name])) {
  1717. return false;
  1718. }
  1719. $perm = null;
  1720. if ($this->access) {
  1721. $perm = call_user_func($this->access, $name, $path, $this->options['accessControlData'], $this);
  1722. if ($perm !== null) {
  1723. return !!$perm;
  1724. }
  1725. }
  1726. if ($this->separator != '/') {
  1727. $path = str_replace($this->separator, '/', $this->_relpath($path));
  1728. } else {
  1729. $path = $this->_relpath($path);
  1730. }
  1731. $path = '/'.$path;
  1732. for ($i = 0, $c = count($this->attributes); $i < $c; $i++) {
  1733. $attrs = $this->attributes[$i];
  1734. if (isset($attrs[$name]) && isset($attrs['pattern']) && preg_match($attrs['pattern'], $path)) {
  1735. $perm = $attrs[$name];
  1736. }
  1737. }
  1738. return $perm === null ? (is_null($val)? $this->defaults[$name] : $val) : !!$perm;
  1739. }
  1740. /**
  1741. * Return true if file with given name can be created in given folder.
  1742. *
  1743. * @param string $dir parent dir path
  1744. * @param string $name new file name
  1745. * @return bool
  1746. * @author Dmitry (dio) Levashov
  1747. **/
  1748. protected function allowCreate($dir, $name) {
  1749. $path = $this->_joinPath($dir, $name);
  1750. $perm = null;
  1751. if ($this->access) {
  1752. $perm = call_user_func($this->access, 'write', $path, $this->options['accessControlData'], $this);
  1753. if ($perm !== null) {
  1754. return !!$perm;
  1755. }
  1756. }
  1757. $testPath = $this->separator.$this->_relpath($path);
  1758. for ($i = 0, $c = count($this->attributes); $i < $c; $i++) {
  1759. $attrs = $this->attributes[$i];
  1760. if (isset($attrs['write']) && isset($attrs['pattern']) && preg_match($attrs['pattern'], $testPath)) {
  1761. $perm = $attrs['write'];
  1762. }
  1763. }
  1764. return $perm === null ? true : $perm;
  1765. }
  1766. /**
  1767. * Return fileinfo
  1768. *
  1769. * @param string $path file cache
  1770. * @return array
  1771. * @author Dmitry (dio) Levashov
  1772. **/
  1773. protected function stat($path) {
  1774. if ($path === false) {
  1775. return false;
  1776. }
  1777. return isset($this->cache[$path])
  1778. ? $this->cache[$path]
  1779. : $this->updateCache($path, $this->_stat($path));
  1780. }
  1781. /**
  1782. * Put file stat in cache and return it
  1783. *
  1784. * @param string $path file path
  1785. * @param array $stat file stat
  1786. * @return array
  1787. * @author Dmitry (dio) Levashov
  1788. **/
  1789. protected function updateCache($path, $stat) {
  1790. if (empty($stat) || !is_array($stat)) {
  1791. return $this->cache[$path] = array();
  1792. }
  1793. $stat['hash'] = $this->encode($path);
  1794. $root = $path == $this->root;
  1795. if ($root) {
  1796. $stat['volumeid'] = $this->id;
  1797. if ($this->rootName) {
  1798. $stat['name'] = $this->rootName;
  1799. }
  1800. } else {
  1801. if (!isset($stat['name']) || !strlen($stat['name'])) {
  1802. $stat['name'] = $this->_basename($path);
  1803. }
  1804. if (empty($stat['phash'])) {
  1805. $stat['phash'] = $this->encode($this->_dirname($path));
  1806. }
  1807. }
  1808. // fix name if required
  1809. if ($this->options['utf8fix'] && $this->options['utf8patterns'] && $this->options['utf8replace']) {
  1810. $stat['name'] = json_decode(str_replace($this->options['utf8patterns'], $this->options['utf8replace'], json_encode($stat['name'])));
  1811. }
  1812. if (empty($stat['mime'])) {
  1813. $stat['mime'] = $this->mimetype($stat['name']);
  1814. }
  1815. // @todo move dateformat to client
  1816. // $stat['date'] = isset($stat['ts'])
  1817. // ? $this->formatDate($stat['ts'])
  1818. // : 'unknown';
  1819. if (!isset($stat['size'])) {
  1820. $stat['size'] = 'unknown';
  1821. }
  1822. $stat['read'] = intval($this->attr($path, 'read', isset($stat['read']) ? !!$stat['read'] : null));
  1823. $stat['write'] = intval($this->attr($path, 'write', isset($stat['write']) ? !!$stat['write'] : null));
  1824. if ($root) {
  1825. $stat['locked'] = 1;
  1826. } elseif ($this->attr($path, 'locked', !empty($stat['locked']))) {
  1827. $stat['locked'] = 1;
  1828. } else {
  1829. unset($stat['locked']);
  1830. }
  1831. if ($root) {
  1832. unset($stat['hidden']);
  1833. } elseif ($this->attr($path, 'hidden', !empty($stat['hidden']))
  1834. || !$this->mimeAccepted($stat['mime'])) {
  1835. $stat['hidden'] = $root ? 0 : 1;
  1836. } else {
  1837. unset($stat['hidden']);
  1838. }
  1839. if ($stat['read'] && empty($stat['hidden'])) {
  1840. if ($stat['mime'] == 'directory') {
  1841. // for dir - check for subdirs
  1842. if ($this->options['checkSubfolders']) {
  1843. if (isset($stat['dirs'])) {
  1844. if ($stat['dirs']) {
  1845. $stat['dirs'] = 1;
  1846. } else {
  1847. unset($stat['dirs']);
  1848. }
  1849. } elseif (!empty($stat['alias']) && !empty($stat['target'])) {
  1850. $stat['dirs'] = isset($this->cache[$stat['target']])
  1851. ? intval(isset($this->cache[$stat['target']]['dirs']))
  1852. : $this->_subdirs($stat['target']);
  1853. } elseif ($this->_subdirs($path)) {
  1854. $stat['dirs'] = 1;
  1855. }
  1856. } else {
  1857. $stat['dirs'] = 1;
  1858. }
  1859. } else {
  1860. // for files - check for thumbnails
  1861. $p = isset($stat['target']) ? $stat['target'] : $path;
  1862. if ($this->tmbURL && !isset($stat['tmb']) && $this->canCreateTmb($p, $stat)) {
  1863. $tmb = $this->gettmb($p, $stat);
  1864. $stat['tmb'] = $tmb ? $tmb : 1;
  1865. }
  1866. }
  1867. }
  1868. if (!empty($stat['alias']) && !empty($stat['target'])) {
  1869. $stat['thash'] = $this->encode($stat['target']);
  1870. unset($stat['target']);
  1871. }
  1872. return $this->cache[$path] = $stat;
  1873. }
  1874. /**
  1875. * Get stat for folder content and put in cache
  1876. *
  1877. * @param string $path
  1878. * @return void
  1879. * @author Dmitry (dio) Levashov
  1880. **/
  1881. protected function cacheDir($path) {
  1882. $this->dirsCache[$path] = array();
  1883. foreach ($this->_scandir($path) as $p) {
  1884. if (($stat = $this->stat($p)) && empty($stat['hidden'])) {
  1885. $this->dirsCache[$path][] = $p;
  1886. }
  1887. }
  1888. }
  1889. /**
  1890. * Clean cache
  1891. *
  1892. * @return void
  1893. * @author Dmitry (dio) Levashov
  1894. **/
  1895. protected function clearcache() {
  1896. $this->cache = $this->dirsCache = array();
  1897. }
  1898. /**
  1899. * Return file mimetype
  1900. *
  1901. * @param string $path file path
  1902. * @return string
  1903. * @author Dmitry (dio) Levashov
  1904. **/
  1905. protected function mimetype($path, $name = '') {
  1906. $type = '';
  1907. if ($this->mimeDetect == 'finfo') {
  1908. if ($type = @finfo_file($this->finfo, $path)) {
  1909. if ($name === '') {
  1910. $name = $path;
  1911. }
  1912. $ext = (false === $pos = strrpos($name, '.')) ? '' : substr($name, $pos + 1);
  1913. if ($ext && preg_match('~^application/(?:octet-stream|(?:x-)?zip)~', $type)) {
  1914. if (isset(elFinderVolumeDriver::$mimetypes[$ext])) $type = elFinderVolumeDriver::$mimetypes[$ext];
  1915. }
  1916. }
  1917. } elseif ($type == 'mime_content_type') {
  1918. $type = mime_content_type($path);
  1919. } else {
  1920. $type = elFinderVolumeDriver::mimetypeInternalDetect($path);
  1921. }
  1922. $type = explode(';', $type);
  1923. $type = trim($type[0]);
  1924. if (in_array($type, array('application/x-empty', 'inode/x-empty'))) {
  1925. // finfo return this mime for empty files
  1926. $type = 'text/plain';
  1927. } elseif ($type == 'application/x-zip') {
  1928. // http://elrte.org/redmine/issues/163
  1929. $type = 'application/zip';
  1930. }
  1931. return $type == 'unknown' && $this->mimeDetect != 'internal'
  1932. ? elFinderVolumeDriver::mimetypeInternalDetect($path)
  1933. : $type;
  1934. }
  1935. /**
  1936. * Detect file mimetype using "internal" method
  1937. *
  1938. * @param string $path file path
  1939. * @return string
  1940. * @author Dmitry (dio) Levashov
  1941. **/
  1942. static protected function mimetypeInternalDetect($path) {
  1943. $pinfo = pathinfo($path);
  1944. $ext = isset($pinfo['extension']) ? strtolower($pinfo['extension']) : '';
  1945. return isset(elFinderVolumeDriver::$mimetypes[$ext]) ? elFinderVolumeDriver::$mimetypes[$ext] : 'unknown';
  1946. }
  1947. /**
  1948. * Return file/total directory size
  1949. *
  1950. * @param string $path file path
  1951. * @return int
  1952. * @author Dmitry (dio) Levashov
  1953. **/
  1954. protected function countSize($path) {
  1955. $stat = $this->stat($path);
  1956. if (empty($stat) || !$stat['read'] || !empty($stat['hidden'])) {
  1957. return 'unknown';
  1958. }
  1959. if ($stat['mime'] != 'directory') {
  1960. return $stat['size'];
  1961. }
  1962. $subdirs = $this->options['checkSubfolders'];
  1963. $this->options['checkSubfolders'] = true;
  1964. $result = 0;
  1965. foreach ($this->getScandir($path) as $stat) {
  1966. $size = $stat['mime'] == 'directory' && $stat['read']
  1967. ? $this->countSize($this->_joinPath($path, $stat['name']))
  1968. : (isset($stat['size']) ? intval($stat['size']) : 0);
  1969. if ($size > 0) {
  1970. $result += $size;
  1971. }
  1972. }
  1973. $this->options['checkSubfolders'] = $subdirs;
  1974. return $result;
  1975. }
  1976. /**
  1977. * Return true if all mimes is directory or files
  1978. *
  1979. * @param string $mime1 mimetype
  1980. * @param string $mime2 mimetype
  1981. * @return bool
  1982. * @author Dmitry (dio) Levashov
  1983. **/
  1984. protected function isSameType($mime1, $mime2) {
  1985. return ($mime1 == 'directory' && $mime1 == $mime2) || ($mime1 != 'directory' && $mime2 != 'directory');
  1986. }
  1987. /**
  1988. * If file has required attr == $val - return file path,
  1989. * If dir has child with has required attr == $val - return child path
  1990. *
  1991. * @param string $path file path
  1992. * @param string $attr attribute name
  1993. * @param bool $val attribute value
  1994. * @return string|false
  1995. * @author Dmitry (dio) Levashov
  1996. **/
  1997. protected function closestByAttr($path, $attr, $val) {
  1998. $stat = $this->stat($path);
  1999. if (empty($stat)) {
  2000. return false;
  2001. }
  2002. $v = isset($stat[$attr]) ? $stat[$attr] : false;
  2003. if ($v == $val) {
  2004. return $path;
  2005. }
  2006. return $stat['mime'] == 'directory'
  2007. ? $this->childsByAttr($path, $attr, $val)
  2008. : false;
  2009. }
  2010. /**
  2011. * Return first found children with required attr == $val
  2012. *
  2013. * @param string $path file path
  2014. * @param string $attr attribute name
  2015. * @param bool $val attribute value
  2016. * @return string|false
  2017. * @author Dmitry (dio) Levashov
  2018. **/
  2019. protected function childsByAttr($path, $attr, $val) {
  2020. foreach ($this->_scandir($path) as $p) {
  2021. if (($_p = $this->closestByAttr($p, $attr, $val)) != false) {
  2022. return $_p;
  2023. }
  2024. }
  2025. return false;
  2026. }
  2027. /***************** get content *******************/
  2028. /**
  2029. * Return required dir's files info.
  2030. * If onlyMimes is set - return only dirs and files of required mimes
  2031. *
  2032. * @param string $path dir path
  2033. * @return array
  2034. * @author Dmitry (dio) Levashov
  2035. **/
  2036. protected function getScandir($path) {
  2037. $files = array();
  2038. !isset($this->dirsCache[$path]) && $this->cacheDir($path);
  2039. foreach ($this->dirsCache[$path] as $p) {
  2040. if (($stat = $this->stat($p)) && empty($stat['hidden'])) {
  2041. $files[] = $stat;
  2042. }
  2043. }
  2044. return $files;
  2045. }
  2046. /**
  2047. * Return subdirs tree
  2048. *
  2049. * @param string $path parent dir path
  2050. * @param int $deep tree deep
  2051. * @return array
  2052. * @author Dmitry (dio) Levashov
  2053. **/
  2054. protected function gettree($path, $deep, $exclude='') {
  2055. $dirs = array();
  2056. !isset($this->dirsCache[$path]) && $this->cacheDir($path);
  2057. foreach ($this->dirsCache[$path] as $p) {
  2058. $stat = $this->stat($p);
  2059. if ($stat && empty($stat['hidden']) && $p != $exclude && $stat['mime'] == 'directory') {
  2060. $dirs[] = $stat;
  2061. if ($deep > 0 && !empty($stat['dirs'])) {
  2062. $dirs = array_merge($dirs, $this->gettree($p, $deep-1));
  2063. }
  2064. }
  2065. }
  2066. return $dirs;
  2067. }
  2068. /**
  2069. * Recursive files search
  2070. *
  2071. * @param string $path dir path
  2072. * @param string $q search string
  2073. * @param array $mimes
  2074. * @return array
  2075. * @author Dmitry (dio) Levashov
  2076. **/
  2077. protected function doSearch($path, $q, $mimes) {
  2078. $result = array();
  2079. foreach($this->_scandir($path) as $p) {
  2080. $stat = $this->stat($p);
  2081. if (!$stat) { // invalid links
  2082. continue;
  2083. }
  2084. if (!empty($stat['hidden']) || !$this->mimeAccepted($stat['mime'])) {
  2085. continue;
  2086. }
  2087. $name = $stat['name'];
  2088. if ($this->stripos($name, $q) !== false) {
  2089. $stat['path'] = $this->_path($p);
  2090. if ($this->URL && !isset($stat['url'])) {
  2091. $stat['url'] = $this->URL . str_replace($this->separator, '/', substr($p, strlen($this->root) + 1));
  2092. }
  2093. $result[] = $stat;
  2094. }
  2095. if ($stat['mime'] == 'directory' && $stat['read'] && !isset($stat['alias'])) {
  2096. $result = array_merge($result, $this->doSearch($p, $q, $mimes));
  2097. }
  2098. }
  2099. return $result;
  2100. }
  2101. /********************** manuipulations ******************/
  2102. /**
  2103. * Copy file/recursive copy dir only in current volume.
  2104. * Return new file path or false.
  2105. *
  2106. * @param string $src source path
  2107. * @param string $dst destination dir path
  2108. * @param string $name new file name (optionaly)
  2109. * @return string|false
  2110. * @author Dmitry (dio) Levashov
  2111. **/
  2112. protected function copy($src, $dst, $name) {
  2113. $srcStat = $this->stat($src);
  2114. $this->clearcache();
  2115. if (!empty($srcStat['thash'])) {
  2116. $target = $this->decode($srcStat['thash']);
  2117. $stat = $this->stat($target);
  2118. $this->clearcache();
  2119. return $stat && $this->_symlink($target, $dst, $name)
  2120. ? $this->_joinPath($dst, $name)
  2121. : $this->setError(elFinder::ERROR_COPY, $this->_path($src));
  2122. }
  2123. if ($srcStat['mime'] == 'directory') {
  2124. $test = $this->stat($this->_joinPath($dst, $name));
  2125. if (($test && $test['mime'] != 'directory') || !$this->_mkdir($dst, $name)) {
  2126. return $this->setError(elFinder::ERROR_COPY, $this->_path($src));
  2127. }
  2128. $dst = $this->_joinPath($dst, $name);
  2129. foreach ($this->getScandir($src) as $stat) {
  2130. if (empty($stat['hidden'])) {
  2131. $name = $stat['name'];
  2132. if (!$this->copy($this->_joinPath($src, $name), $dst, $name)) {
  2133. $this->remove($dst, true); // fall back
  2134. return false;
  2135. }
  2136. }
  2137. }
  2138. $this->clearcache();
  2139. return $dst;
  2140. }
  2141. return $this->_copy($src, $dst, $name)
  2142. ? $this->_joinPath($dst, $name)
  2143. : $this->setError(elFinder::ERROR_COPY, $this->_path($src));
  2144. }
  2145. /**
  2146. * Move file
  2147. * Return new file path or false.
  2148. *
  2149. * @param string $src source path
  2150. * @param string $dst destination dir path
  2151. * @param string $name new file name
  2152. * @return string|false
  2153. * @author Dmitry (dio) Levashov
  2154. **/
  2155. protected function move($src, $dst, $name) {
  2156. $stat = $this->stat($src);
  2157. $stat['realpath'] = $src;
  2158. $this->rmTmb($stat); // can not do rmTmb() after _move()
  2159. $this->clearcache();
  2160. if ($this->_move($src, $dst, $name)) {
  2161. $this->removed[] = $stat;
  2162. return $this->_joinPath($dst, $name);
  2163. }
  2164. return $this->setError(elFinder::ERROR_MOVE, $this->_path($src));
  2165. }
  2166. /**
  2167. * Copy file from another volume.
  2168. * Return new file path or false.
  2169. *
  2170. * @param Object $volume source volume
  2171. * @param string $src source file hash
  2172. * @param string $destination destination dir path
  2173. * @param string $name file name
  2174. * @return string|false
  2175. * @author Dmitry (dio) Levashov
  2176. **/
  2177. protected function copyFrom($volume, $src, $destination, $name) {
  2178. if (($source = $volume->file($src)) == false) {
  2179. return $this->setError(elFinder::ERROR_COPY, '#'.$src, $volume->error());
  2180. }
  2181. $errpath = $volume->path($src);
  2182. if (!$this->nameAccepted($source['name'])) {
  2183. return $this->setError(elFinder::ERROR_COPY, $errpath, elFinder::ERROR_INVALID_NAME);
  2184. }
  2185. if (!$source['read']) {
  2186. return $this->setError(elFinder::ERROR_COPY, $errpath, elFinder::ERROR_PERM_DENIED);
  2187. }
  2188. if ($source['mime'] == 'directory') {
  2189. $stat = $this->stat($this->_joinPath($destination, $name));
  2190. $this->clearcache();
  2191. if ((!$stat || $stat['mime'] != 'directory') && !$this->_mkdir($destination, $name)) {
  2192. return $this->setError(elFinder::ERROR_COPY, $errpath);
  2193. }
  2194. $path = $this->_joinPath($destination, $name);
  2195. foreach ($volume->scandir($src) as $entr) {
  2196. if (!$this->copyFrom($volume, $entr['hash'], $path, $entr['name'])) {
  2197. return false;
  2198. }
  2199. }
  2200. } else {
  2201. // $mime = $source['mime'];
  2202. // $w = $h = 0;
  2203. if (($dim = $volume->dimensions($src))) {
  2204. $s = explode('x', $dim);
  2205. $source['width'] = $s[0];
  2206. $source['height'] = $s[1];
  2207. }
  2208. if (($fp = $volume->open($src)) == false
  2209. || ($path = $this->_save($fp, $destination, $name, $source)) == false) {
  2210. $fp && $volume->close($fp, $src);
  2211. return $this->setError(elFinder::ERROR_COPY, $errpath);
  2212. }
  2213. $volume->close($fp, $src);
  2214. }
  2215. return $path;
  2216. }
  2217. /**
  2218. * Remove file/ recursive remove dir
  2219. *
  2220. * @param string $path file path
  2221. * @param bool $force try to remove even if file locked
  2222. * @return bool
  2223. * @author Dmitry (dio) Levashov
  2224. **/
  2225. protected function remove($path, $force = false) {
  2226. $stat = $this->stat($path);
  2227. $stat['realpath'] = $path;
  2228. $this->rmTmb($stat);
  2229. $this->clearcache();
  2230. if (empty($stat)) {
  2231. return $this->setError(elFinder::ERROR_RM, $this->_path($path), elFinder::ERROR_FILE_NOT_FOUND);
  2232. }
  2233. if (!$force && !empty($stat['locked'])) {
  2234. return $this->setError(elFinder::ERROR_LOCKED, $this->_path($path));
  2235. }
  2236. if ($stat['mime'] == 'directory') {
  2237. foreach ($this->_scandir($path) as $p) {
  2238. $name = $this->_basename($p);
  2239. if ($name != '.' && $name != '..' && !$this->remove($p)) {
  2240. return false;
  2241. }
  2242. }
  2243. if (!$this->_rmdir($path)) {
  2244. return $this->setError(elFinder::ERROR_RM, $this->_path($path));
  2245. }
  2246. } else {
  2247. if (!$this->_unlink($path)) {
  2248. return $this->setError(elFinder::ERROR_RM, $this->_path($path));
  2249. }
  2250. }
  2251. $this->removed[] = $stat;
  2252. return true;
  2253. }
  2254. /************************* thumbnails **************************/
  2255. /**
  2256. * Return thumbnail file name for required file
  2257. *
  2258. * @param array $stat file stat
  2259. * @return string
  2260. * @author Dmitry (dio) Levashov
  2261. **/
  2262. protected function tmbname($stat) {
  2263. return $stat['hash'].$stat['ts'].'.png';
  2264. }
  2265. /**
  2266. * Return thumnbnail name if exists
  2267. *
  2268. * @param string $path file path
  2269. * @param array $stat file stat
  2270. * @return string|false
  2271. * @author Dmitry (dio) Levashov
  2272. **/
  2273. protected function gettmb($path, $stat) {
  2274. if ($this->tmbURL && $this->tmbPath) {
  2275. // file itself thumnbnail
  2276. if (strpos($path, $this->tmbPath) === 0) {
  2277. return basename($path);
  2278. }
  2279. $name = $this->tmbname($stat);
  2280. if (file_exists($this->tmbPath.DIRECTORY_SEPARATOR.$name)) {
  2281. return $name;
  2282. }
  2283. }
  2284. return false;
  2285. }
  2286. /**
  2287. * Return true if thumnbnail for required file can be created
  2288. *
  2289. * @param string $path thumnbnail path
  2290. * @param array $stat file stat
  2291. * @return string|bool
  2292. * @author Dmitry (dio) Levashov
  2293. **/
  2294. protected function canCreateTmb($path, $stat) {
  2295. return $this->tmbPathWritable
  2296. && strpos($path, $this->tmbPath) === false // do not create thumnbnail for thumnbnail
  2297. && $this->imgLib
  2298. && strpos($stat['mime'], 'image') === 0
  2299. && ($this->imgLib == 'gd' ? $stat['mime'] == 'image/jpeg' || $stat['mime'] == 'image/png' || $stat['mime'] == 'image/gif' : true);
  2300. }
  2301. /**
  2302. * Return true if required file can be resized.
  2303. * By default - the same as canCreateTmb
  2304. *
  2305. * @param string $path thumnbnail path
  2306. * @param array $stat file stat
  2307. * @return string|bool
  2308. * @author Dmitry (dio) Levashov
  2309. **/
  2310. protected function canResize($path, $stat) {
  2311. return $this->canCreateTmb($path, $stat);
  2312. }
  2313. /**
  2314. * Create thumnbnail and return it's URL on success
  2315. *
  2316. * @param string $path file path
  2317. * @param string $mime file mime type
  2318. * @return string|false
  2319. * @author Dmitry (dio) Levashov
  2320. **/
  2321. protected function createTmb($path, $stat) {
  2322. if (!$stat || !$this->canCreateTmb($path, $stat)) {
  2323. return false;
  2324. }
  2325. $name = $this->tmbname($stat);
  2326. $tmb = $this->tmbPath.DIRECTORY_SEPARATOR.$name;
  2327. // copy image into tmbPath so some drivers does not store files on local fs
  2328. if (($src = $this->_fopen($path, 'rb')) == false) {
  2329. return false;
  2330. }
  2331. if (($trg = fopen($tmb, 'wb')) == false) {
  2332. $this->_fclose($src, $path);
  2333. return false;
  2334. }
  2335. while (!feof($src)) {
  2336. fwrite($trg, fread($src, 8192));
  2337. }
  2338. $this->_fclose($src, $path);
  2339. fclose($trg);
  2340. $result = false;
  2341. $tmbSize = $this->tmbSize;
  2342. if (($s = getimagesize($tmb)) == false) {
  2343. return false;
  2344. }
  2345. /* If image smaller or equal thumbnail size - just fitting to thumbnail square */
  2346. if ($s[0] <= $tmbSize && $s[1] <= $tmbSize) {
  2347. $result = $this->imgSquareFit($tmb, $tmbSize, $tmbSize, 'center', 'middle', $this->options['tmbBgColor'], 'png' );
  2348. } else {
  2349. if ($this->options['tmbCrop']) {
  2350. /* Resize and crop if image bigger than thumbnail */
  2351. if (!(($s[0] > $tmbSize && $s[1] <= $tmbSize) || ($s[0] <= $tmbSize && $s[1] > $tmbSize) ) || ($s[0] > $tmbSize && $s[1] > $tmbSize)) {
  2352. $result = $this->imgResize($tmb, $tmbSize, $tmbSize, true, false, 'png');
  2353. }
  2354. if (($s = getimagesize($tmb)) != false) {
  2355. $x = $s[0] > $tmbSize ? intval(($s[0] - $tmbSize)/2) : 0;
  2356. $y = $s[1] > $tmbSize ? intval(($s[1] - $tmbSize)/2) : 0;
  2357. $result = $this->imgCrop($tmb, $tmbSize, $tmbSize, $x, $y, 'png');
  2358. }
  2359. } else {
  2360. $result = $this->imgResize($tmb, $tmbSize, $tmbSize, true, true, 'png');
  2361. }
  2362. $result = $this->imgSquareFit($tmb, $tmbSize, $tmbSize, 'center', 'middle', $this->options['tmbBgColor'], 'png' );
  2363. }
  2364. if (!$result) {
  2365. unlink($tmb);
  2366. return false;
  2367. }
  2368. return $name;
  2369. }
  2370. /**
  2371. * Resize image
  2372. *
  2373. * @param string $path image file
  2374. * @param int $width new width
  2375. * @param int $height new height
  2376. * @param bool $keepProportions crop image
  2377. * @param bool $resizeByBiggerSide resize image based on bigger side if true
  2378. * @param string $destformat image destination format
  2379. * @return string|false
  2380. * @author Dmitry (dio) Levashov
  2381. * @author Alexey Sukhotin
  2382. **/
  2383. protected function imgResize($path, $width, $height, $keepProportions = false, $resizeByBiggerSide = true, $destformat = null) {
  2384. if (($s = @getimagesize($path)) == false) {
  2385. return false;
  2386. }
  2387. $result = false;
  2388. list($size_w, $size_h) = array($width, $height);
  2389. if ($keepProportions == true) {
  2390. list($orig_w, $orig_h, $new_w, $new_h) = array($s[0], $s[1], $width, $height);
  2391. /* Calculating image scale width and height */
  2392. $xscale = $orig_w / $new_w;
  2393. $yscale = $orig_h / $new_h;
  2394. /* Resizing by biggest side */
  2395. if ($resizeByBiggerSide) {
  2396. if ($orig_w > $orig_h) {
  2397. $size_h = $orig_h * $width / $orig_w;
  2398. $size_w = $width;
  2399. } else {
  2400. $size_w = $orig_w * $height / $orig_h;
  2401. $size_h = $height;
  2402. }
  2403. } else {
  2404. if ($orig_w > $orig_h) {
  2405. $size_w = $orig_w * $height / $orig_h;
  2406. $size_h = $height;
  2407. } else {
  2408. $size_h = $orig_h * $width / $orig_w;
  2409. $size_w = $width;
  2410. }
  2411. }
  2412. }
  2413. switch ($this->imgLib) {
  2414. case 'imagick':
  2415. try {
  2416. $img = new imagick($path);
  2417. } catch (Exception $e) {
  2418. return false;
  2419. }
  2420. $img->resizeImage($size_w, $size_h, Imagick::FILTER_LANCZOS, true);
  2421. $result = $img->writeImage($path);
  2422. return $result ? $path : false;
  2423. break;
  2424. case 'gd':
  2425. $img = self::gdImageCreate($path,$s['mime']);
  2426. if ($img && false != ($tmp = imagecreatetruecolor($size_w, $size_h))) {
  2427. self::gdImageBackground($tmp,$this->options['tmbBgColor']);
  2428. if (!imagecopyresampled($tmp, $img, 0, 0, 0, 0, $size_w, $size_h, $s[0], $s[1])) {
  2429. return false;
  2430. }
  2431. $result = self::gdImage($tmp, $path, $destformat, $s['mime']);
  2432. imagedestroy($img);
  2433. imagedestroy($tmp);
  2434. return $result ? $path : false;
  2435. }
  2436. break;
  2437. }
  2438. return false;
  2439. }
  2440. /**
  2441. * Crop image
  2442. *
  2443. * @param string $path image file
  2444. * @param int $width crop width
  2445. * @param int $height crop height
  2446. * @param bool $x crop left offset
  2447. * @param bool $y crop top offset
  2448. * @param string $destformat image destination format
  2449. * @return string|false
  2450. * @author Dmitry (dio) Levashov
  2451. * @author Alexey Sukhotin
  2452. **/
  2453. protected function imgCrop($path, $width, $height, $x, $y, $destformat = null) {
  2454. if (($s = @getimagesize($path)) == false) {
  2455. return false;
  2456. }
  2457. $result = false;
  2458. switch ($this->imgLib) {
  2459. case 'imagick':
  2460. try {
  2461. $img = new imagick($path);
  2462. } catch (Exception $e) {
  2463. return false;
  2464. }
  2465. $img->cropImage($width, $height, $x, $y);
  2466. $result = $img->writeImage($path);
  2467. return $result ? $path : false;
  2468. break;
  2469. case 'gd':
  2470. $img = self::gdImageCreate($path,$s['mime']);
  2471. if ($img && false != ($tmp = imagecreatetruecolor($width, $height))) {
  2472. self::gdImageBackground($tmp,$this->options['tmbBgColor']);
  2473. $size_w = $width;
  2474. $size_h = $height;
  2475. if ($s[0] < $width || $s[1] < $height) {
  2476. $size_w = $s[0];
  2477. $size_h = $s[1];
  2478. }
  2479. if (!imagecopy($tmp, $img, 0, 0, $x, $y, $size_w, $size_h)) {
  2480. return false;
  2481. }
  2482. $result = self::gdImage($tmp, $path, $destformat, $s['mime']);
  2483. imagedestroy($img);
  2484. imagedestroy($tmp);
  2485. return $result ? $path : false;
  2486. }
  2487. break;
  2488. }
  2489. return false;
  2490. }
  2491. /**
  2492. * Put image to square
  2493. *
  2494. * @param string $path image file
  2495. * @param int $width square width
  2496. * @param int $height square height
  2497. * @param int $align reserved
  2498. * @param int $valign reserved
  2499. * @param string $bgcolor square background color in #rrggbb format
  2500. * @param string $destformat image destination format
  2501. * @return string|false
  2502. * @author Dmitry (dio) Levashov
  2503. * @author Alexey Sukhotin
  2504. **/
  2505. protected function imgSquareFit($path, $width, $height, $align = 'center', $valign = 'middle', $bgcolor = '#0000ff', $destformat = null) {
  2506. if (($s = @getimagesize($path)) == false) {
  2507. return false;
  2508. }
  2509. $result = false;
  2510. /* Coordinates for image over square aligning */
  2511. $y = ceil(abs($height - $s[1]) / 2);
  2512. $x = ceil(abs($width - $s[0]) / 2);
  2513. switch ($this->imgLib) {
  2514. case 'imagick':
  2515. try {
  2516. $img = new imagick($path);
  2517. } catch (Exception $e) {
  2518. return false;
  2519. }
  2520. $img1 = new Imagick();
  2521. $img1->newImage($width, $height, new ImagickPixel($bgcolor));
  2522. $img1->setImageColorspace($img->getImageColorspace());
  2523. $img1->setImageFormat($destformat != null ? $destformat : $img->getFormat());
  2524. $img1->compositeImage( $img, imagick::COMPOSITE_OVER, $x, $y );
  2525. $result = $img1->writeImage($path);
  2526. return $result ? $path : false;
  2527. break;
  2528. case 'gd':
  2529. $img = self::gdImageCreate($path,$s['mime']);
  2530. if ($img && false != ($tmp = imagecreatetruecolor($width, $height))) {
  2531. self::gdImageBackground($tmp,$bgcolor);
  2532. if (!imagecopy($tmp, $img, $x, $y, 0, 0, $s[0], $s[1])) {
  2533. return false;
  2534. }
  2535. $result = self::gdImage($tmp, $path, $destformat, $s['mime']);
  2536. imagedestroy($img);
  2537. imagedestroy($tmp);
  2538. return $result ? $path : false;
  2539. }
  2540. break;
  2541. }
  2542. return false;
  2543. }
  2544. /**
  2545. * Rotate image
  2546. *
  2547. * @param string $path image file
  2548. * @param int $degree rotete degrees
  2549. * @param string $bgcolor square background color in #rrggbb format
  2550. * @param string $destformat image destination format
  2551. * @return string|false
  2552. * @author nao-pon
  2553. * @author Troex Nevelin
  2554. **/
  2555. protected function imgRotate($path, $degree, $bgcolor = '#ffffff', $destformat = null) {
  2556. if (($s = @getimagesize($path)) == false) {
  2557. return false;
  2558. }
  2559. $result = false;
  2560. switch ($this->imgLib) {
  2561. case 'imagick':
  2562. try {
  2563. $img = new imagick($path);
  2564. } catch (Exception $e) {
  2565. return false;
  2566. }
  2567. $img->rotateImage(new ImagickPixel($bgcolor), $degree);
  2568. $result = $img->writeImage($path);
  2569. return $result ? $path : false;
  2570. break;
  2571. case 'gd':
  2572. $img = self::gdImageCreate($path,$s['mime']);
  2573. $degree = 360 - $degree;
  2574. list($r, $g, $b) = sscanf($bgcolor, "#%02x%02x%02x");
  2575. $bgcolor = imagecolorallocate($img, $r, $g, $b);
  2576. $tmp = imageRotate($img, $degree, (int)$bgcolor);
  2577. $result = self::gdImage($tmp, $path, $destformat, $s['mime']);
  2578. imageDestroy($img);
  2579. imageDestroy($tmp);
  2580. return $result ? $path : false;
  2581. break;
  2582. }
  2583. return false;
  2584. }
  2585. /**
  2586. * Execute shell command
  2587. *
  2588. * @param string $command command line
  2589. * @param array $output stdout strings
  2590. * @param array $return_var process exit code
  2591. * @param array $error_output stderr strings
  2592. * @return int exit code
  2593. * @author Alexey Sukhotin
  2594. **/
  2595. protected function procExec($command , array &$output = null, &$return_var = -1, array &$error_output = null) {
  2596. $descriptorspec = array(
  2597. 0 => array("pipe", "r"), // stdin
  2598. 1 => array("pipe", "w"), // stdout
  2599. 2 => array("pipe", "w") // stderr
  2600. );
  2601. $process = proc_open($command, $descriptorspec, $pipes, null, null);
  2602. if (is_resource($process)) {
  2603. fclose($pipes[0]);
  2604. $tmpout = '';
  2605. $tmperr = '';
  2606. $output = stream_get_contents($pipes[1]);
  2607. $error_output = stream_get_contents($pipes[2]);
  2608. fclose($pipes[1]);
  2609. fclose($pipes[2]);
  2610. $return_var = proc_close($process);
  2611. }
  2612. return $return_var;
  2613. }
  2614. /**
  2615. * Remove thumbnail, also remove recursively if stat is directory
  2616. *
  2617. * @param string $stat file stat
  2618. * @return void
  2619. * @author Dmitry (dio) Levashov
  2620. * @author Naoki Sawada
  2621. * @author Troex Nevelin
  2622. **/
  2623. protected function rmTmb($stat) {
  2624. if ($stat['mime'] === 'directory') {
  2625. foreach ($this->_scandir($this->decode($stat['hash'])) as $p) {
  2626. $name = $this->_basename($p);
  2627. $name != '.' && $name != '..' && $this->rmTmb($this->stat($p));
  2628. }
  2629. } else if (!empty($stat['tmb']) && $stat['tmb'] != "1") {
  2630. $tmb = $this->tmbPath.DIRECTORY_SEPARATOR.$stat['tmb'];
  2631. file_exists($tmb) && @unlink($tmb);
  2632. clearstatcache();
  2633. }
  2634. }
  2635. /**
  2636. * Create an gd image according to the specified mime type
  2637. *
  2638. * @param string $path image file
  2639. * @param string $mime
  2640. * @return gd image resource identifier
  2641. */
  2642. protected function gdImageCreate($path,$mime){
  2643. switch($mime){
  2644. case 'image/jpeg':
  2645. return imagecreatefromjpeg($path);
  2646. case 'image/png':
  2647. return imagecreatefrompng($path);
  2648. case 'image/gif':
  2649. return imagecreatefromgif($path);
  2650. case 'image/xbm':
  2651. return imagecreatefromxbm($path);
  2652. }
  2653. return false;
  2654. }
  2655. /**
  2656. * Output gd image to file
  2657. *
  2658. * @param resource $image gd image resource
  2659. * @param string $filename The path to save the file to.
  2660. * @param string $destformat The Image type to use for $filename
  2661. * @param string $mime The original image mime type
  2662. */
  2663. protected function gdImage($image, $filename, $destformat, $mime ){
  2664. if ($destformat == 'jpg' || ($destformat == null && $mime == 'image/jpeg')) {
  2665. return imagejpeg($image, $filename, 100);
  2666. }
  2667. if ($destformat == 'gif' || ($destformat == null && $mime == 'image/gif')) {
  2668. return imagegif($image, $filename, 7);
  2669. }
  2670. return imagepng($image, $filename, 7);
  2671. }
  2672. /**
  2673. * Assign the proper background to a gd image
  2674. *
  2675. * @param resource $image gd image resource
  2676. * @param string $bgcolor background color in #rrggbb format
  2677. */
  2678. protected function gdImageBackground($image, $bgcolor){
  2679. if( $bgcolor == 'transparent' ){
  2680. imagesavealpha($image,true);
  2681. $bgcolor1 = imagecolorallocatealpha($image, 255, 255, 255, 127);
  2682. }else{
  2683. list($r, $g, $b) = sscanf($bgcolor, "#%02x%02x%02x");
  2684. $bgcolor1 = imagecolorallocate($image, $r, $g, $b);
  2685. }
  2686. imagefill($image, 0, 0, $bgcolor1);
  2687. }
  2688. /*********************** misc *************************/
  2689. /**
  2690. * Return smart formatted date
  2691. *
  2692. * @param int $ts file timestamp
  2693. * @return string
  2694. * @author Dmitry (dio) Levashov
  2695. **/
  2696. // protected function formatDate($ts) {
  2697. // if ($ts > $this->today) {
  2698. // return 'Today '.date($this->options['timeFormat'], $ts);
  2699. // }
  2700. //
  2701. // if ($ts > $this->yesterday) {
  2702. // return 'Yesterday '.date($this->options['timeFormat'], $ts);
  2703. // }
  2704. //
  2705. // return date($this->options['dateFormat'], $ts);
  2706. // }
  2707. /**
  2708. * Find position of first occurrence of string in a string with multibyte support
  2709. *
  2710. * @param string $haystack The string being checked.
  2711. * @param string $needle The string to find in haystack.
  2712. * @param int $offset The search offset. If it is not specified, 0 is used.
  2713. * @return int|bool
  2714. * @author Alexey Sukhotin
  2715. **/
  2716. protected function stripos($haystack , $needle , $offset = 0) {
  2717. if (function_exists('mb_stripos')) {
  2718. return mb_stripos($haystack , $needle , $offset);
  2719. } else if (function_exists('mb_strtolower') && function_exists('mb_strpos')) {
  2720. return mb_strpos(mb_strtolower($haystack), mb_strtolower($needle), $offset);
  2721. }
  2722. return stripos($haystack , $needle , $offset);
  2723. }
  2724. /**==================================* abstract methods *====================================**/
  2725. /*********************** paths/urls *************************/
  2726. /**
  2727. * Return parent directory path
  2728. *
  2729. * @param string $path file path
  2730. * @return string
  2731. * @author Dmitry (dio) Levashov
  2732. **/
  2733. abstract protected function _dirname($path);
  2734. /**
  2735. * Return file name
  2736. *
  2737. * @param string $path file path
  2738. * @return string
  2739. * @author Dmitry (dio) Levashov
  2740. **/
  2741. abstract protected function _basename($path);
  2742. /**
  2743. * Join dir name and file name and return full path.
  2744. * Some drivers (db) use int as path - so we give to concat path to driver itself
  2745. *
  2746. * @param string $dir dir path
  2747. * @param string $name file name
  2748. * @return string
  2749. * @author Dmitry (dio) Levashov
  2750. **/
  2751. abstract protected function _joinPath($dir, $name);
  2752. /**
  2753. * Return normalized path
  2754. *
  2755. * @param string $path file path
  2756. * @return string
  2757. * @author Dmitry (dio) Levashov
  2758. **/
  2759. abstract protected function _normpath($path);
  2760. /**
  2761. * Return file path related to root dir
  2762. *
  2763. * @param string $path file path
  2764. * @return string
  2765. * @author Dmitry (dio) Levashov
  2766. **/
  2767. abstract protected function _relpath($path);
  2768. /**
  2769. * Convert path related to root dir into real path
  2770. *
  2771. * @param string $path rel file path
  2772. * @return string
  2773. * @author Dmitry (dio) Levashov
  2774. **/
  2775. abstract protected function _abspath($path);
  2776. /**
  2777. * Return fake path started from root dir.
  2778. * Required to show path on client side.
  2779. *
  2780. * @param string $path file path
  2781. * @return string
  2782. * @author Dmitry (dio) Levashov
  2783. **/
  2784. abstract protected function _path($path);
  2785. /**
  2786. * Return true if $path is children of $parent
  2787. *
  2788. * @param string $path path to check
  2789. * @param string $parent parent path
  2790. * @return bool
  2791. * @author Dmitry (dio) Levashov
  2792. **/
  2793. abstract protected function _inpath($path, $parent);
  2794. /**
  2795. * Return stat for given path.
  2796. * Stat contains following fields:
  2797. * - (int) size file size in b. required
  2798. * - (int) ts file modification time in unix time. required
  2799. * - (string) mime mimetype. required for folders, others - optionally
  2800. * - (bool) read read permissions. required
  2801. * - (bool) write write permissions. required
  2802. * - (bool) locked is object locked. optionally
  2803. * - (bool) hidden is object hidden. optionally
  2804. * - (string) alias for symlinks - link target path relative to root path. optionally
  2805. * - (string) target for symlinks - link target path. optionally
  2806. *
  2807. * If file does not exists - returns empty array or false.
  2808. *
  2809. * @param string $path file path
  2810. * @return array|false
  2811. * @author Dmitry (dio) Levashov
  2812. **/
  2813. abstract protected function _stat($path);
  2814. /***************** file stat ********************/
  2815. /**
  2816. * Return true if path is dir and has at least one childs directory
  2817. *
  2818. * @param string $path dir path
  2819. * @return bool
  2820. * @author Dmitry (dio) Levashov
  2821. **/
  2822. abstract protected function _subdirs($path);
  2823. /**
  2824. * Return object width and height
  2825. * Ususaly used for images, but can be realize for video etc...
  2826. *
  2827. * @param string $path file path
  2828. * @param string $mime file mime type
  2829. * @return string
  2830. * @author Dmitry (dio) Levashov
  2831. **/
  2832. abstract protected function _dimensions($path, $mime);
  2833. /******************** file/dir content *********************/
  2834. /**
  2835. * Return files list in directory
  2836. *
  2837. * @param string $path dir path
  2838. * @return array
  2839. * @author Dmitry (dio) Levashov
  2840. **/
  2841. abstract protected function _scandir($path);
  2842. /**
  2843. * Open file and return file pointer
  2844. *
  2845. * @param string $path file path
  2846. * @param bool $write open file for writing
  2847. * @return resource|false
  2848. * @author Dmitry (dio) Levashov
  2849. **/
  2850. abstract protected function _fopen($path, $mode="rb");
  2851. /**
  2852. * Close opened file
  2853. *
  2854. * @param resource $fp file pointer
  2855. * @param string $path file path
  2856. * @return bool
  2857. * @author Dmitry (dio) Levashov
  2858. **/
  2859. abstract protected function _fclose($fp, $path='');
  2860. /******************** file/dir manipulations *************************/
  2861. /**
  2862. * Create dir and return created dir path or false on failed
  2863. *
  2864. * @param string $path parent dir path
  2865. * @param string $name new directory name
  2866. * @return string|bool
  2867. * @author Dmitry (dio) Levashov
  2868. **/
  2869. abstract protected function _mkdir($path, $name);
  2870. /**
  2871. * Create file and return it's path or false on failed
  2872. *
  2873. * @param string $path parent dir path
  2874. * @param string $name new file name
  2875. * @return string|bool
  2876. * @author Dmitry (dio) Levashov
  2877. **/
  2878. abstract protected function _mkfile($path, $name);
  2879. /**
  2880. * Create symlink
  2881. *
  2882. * @param string $source file to link to
  2883. * @param string $targetDir folder to create link in
  2884. * @param string $name symlink name
  2885. * @return bool
  2886. * @author Dmitry (dio) Levashov
  2887. **/
  2888. abstract protected function _symlink($source, $targetDir, $name);
  2889. /**
  2890. * Copy file into another file (only inside one volume)
  2891. *
  2892. * @param string $source source file path
  2893. * @param string $target target dir path
  2894. * @param string $name file name
  2895. * @return bool
  2896. * @author Dmitry (dio) Levashov
  2897. **/
  2898. abstract protected function _copy($source, $targetDir, $name);
  2899. /**
  2900. * Move file into another parent dir.
  2901. * Return new file path or false.
  2902. *
  2903. * @param string $source source file path
  2904. * @param string $target target dir path
  2905. * @param string $name file name
  2906. * @return string|bool
  2907. * @author Dmitry (dio) Levashov
  2908. **/
  2909. abstract protected function _move($source, $targetDir, $name);
  2910. /**
  2911. * Remove file
  2912. *
  2913. * @param string $path file path
  2914. * @return bool
  2915. * @author Dmitry (dio) Levashov
  2916. **/
  2917. abstract protected function _unlink($path);
  2918. /**
  2919. * Remove dir
  2920. *
  2921. * @param string $path dir path
  2922. * @return bool
  2923. * @author Dmitry (dio) Levashov
  2924. **/
  2925. abstract protected function _rmdir($path);
  2926. /**
  2927. * Create new file and write into it from file pointer.
  2928. * Return new file path or false on error.
  2929. *
  2930. * @param resource $fp file pointer
  2931. * @param string $dir target dir path
  2932. * @param string $name file name
  2933. * @param array $stat file stat (required by some virtual fs)
  2934. * @return bool|string
  2935. * @author Dmitry (dio) Levashov
  2936. **/
  2937. abstract protected function _save($fp, $dir, $name, $stat);
  2938. /**
  2939. * Get file contents
  2940. *
  2941. * @param string $path file path
  2942. * @return string|false
  2943. * @author Dmitry (dio) Levashov
  2944. **/
  2945. abstract protected function _getContents($path);
  2946. /**
  2947. * Write a string to a file
  2948. *
  2949. * @param string $path file path
  2950. * @param string $content new file content
  2951. * @return bool
  2952. * @author Dmitry (dio) Levashov
  2953. **/
  2954. abstract protected function _filePutContents($path, $content);
  2955. /**
  2956. * Extract files from archive
  2957. *
  2958. * @param string $path file path
  2959. * @param array $arc archiver options
  2960. * @return bool
  2961. * @author Dmitry (dio) Levashov,
  2962. * @author Alexey Sukhotin
  2963. **/
  2964. abstract protected function _extract($path, $arc);
  2965. /**
  2966. * Create archive and return its path
  2967. *
  2968. * @param string $dir target dir
  2969. * @param array $files files names list
  2970. * @param string $name archive name
  2971. * @param array $arc archiver options
  2972. * @return string|bool
  2973. * @author Dmitry (dio) Levashov,
  2974. * @author Alexey Sukhotin
  2975. **/
  2976. abstract protected function _archive($dir, $files, $name, $arc);
  2977. /**
  2978. * Detect available archivers
  2979. *
  2980. * @return void
  2981. * @author Dmitry (dio) Levashov,
  2982. * @author Alexey Sukhotin
  2983. **/
  2984. abstract protected function _checkArchivers();
  2985. } // END class