elFinderVolumeLocalFileSystem.class.php 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272
  1. <?php
  2. // Implement similar functionality in PHP 5.2 or 5.3
  3. // http://php.net/manual/class.recursivecallbackfilteriterator.php#110974
  4. if (! class_exists('RecursiveCallbackFilterIterator', false)) {
  5. class RecursiveCallbackFilterIterator extends RecursiveFilterIterator {
  6. public function __construct ( RecursiveIterator $iterator, $callback ) {
  7. $this->callback = $callback;
  8. parent::__construct($iterator);
  9. }
  10. public function accept () {
  11. return call_user_func($this->callback, parent::current(), parent::key(), parent::getInnerIterator());
  12. }
  13. public function getChildren () {
  14. return new self($this->getInnerIterator()->getChildren(), $this->callback);
  15. }
  16. }
  17. }
  18. /**
  19. * elFinder driver for local filesystem.
  20. *
  21. * @author Dmitry (dio) Levashov
  22. * @author Troex Nevelin
  23. **/
  24. class elFinderVolumeLocalFileSystem extends elFinderVolumeDriver {
  25. /**
  26. * Driver id
  27. * Must be started from letter and contains [a-z0-9]
  28. * Used as part of volume id
  29. *
  30. * @var string
  31. **/
  32. protected $driverId = 'l';
  33. /**
  34. * Required to count total archive files size
  35. *
  36. * @var int
  37. **/
  38. protected $archiveSize = 0;
  39. /**
  40. * Is checking stat owner
  41. *
  42. * @var boolean
  43. */
  44. protected $statOwner = false;
  45. /**
  46. * Constructor
  47. * Extend options with required fields
  48. *
  49. * @author Dmitry (dio) Levashov
  50. */
  51. public function __construct() {
  52. $this->options['alias'] = ''; // alias to replace root dir name
  53. $this->options['dirMode'] = 0755; // new dirs mode
  54. $this->options['fileMode'] = 0644; // new files mode
  55. $this->options['quarantine'] = '.quarantine'; // quarantine folder name - required to check archive (must be hidden)
  56. $this->options['rootCssClass'] = 'elfinder-navbar-root-local';
  57. $this->options['followSymLinks'] = true;
  58. $this->options['detectDirIcon'] = ''; // file name that is detected as a folder icon e.g. '.diricon.png'
  59. $this->options['keepTimestamp'] = array('copy', 'move'); // keep timestamp at inner filesystem allowed 'copy', 'move' and 'upload'
  60. $this->options['substituteImg'] = true; // support substitute image with dim command
  61. }
  62. /*********************************************************************/
  63. /* INIT AND CONFIGURE */
  64. /*********************************************************************/
  65. /**
  66. * Prepare driver before mount volume.
  67. * Return true if volume is ready.
  68. *
  69. * @return bool
  70. **/
  71. protected function init() {
  72. // Normalize directory separator for windows
  73. if (DIRECTORY_SEPARATOR !== '/') {
  74. foreach(array('path', 'tmbPath', 'tmpPath', 'quarantine') as $key) {
  75. if (!empty($this->options[$key])) {
  76. $this->options[$key] = str_replace('/', DIRECTORY_SEPARATOR, $this->options[$key]);
  77. }
  78. }
  79. // PHP >= 7.1 Supports UTF-8 path on Windows
  80. if (version_compare(PHP_VERSION, '7.1', '>=')) {
  81. $this->options['encoding'] = '';
  82. $this->options['locale'] = '';
  83. }
  84. }
  85. if (!$cwd = getcwd()) {
  86. return $this->setError('elFinder LocalVolumeDriver requires a result of getcwd().');
  87. }
  88. // detect systemRoot
  89. if (!isset($this->options['systemRoot'])) {
  90. if ($cwd[0] === $this->separator || $this->root[0] === $this->separator) {
  91. $this->systemRoot = $this->separator;
  92. } else if (preg_match('/^([a-zA-Z]:'.preg_quote($this->separator, '/').')/', $this->root, $m)) {
  93. $this->systemRoot = $m[1];
  94. } else if (preg_match('/^([a-zA-Z]:'.preg_quote($this->separator, '/').')/', $cwd, $m)) {
  95. $this->systemRoot = $m[1];
  96. }
  97. }
  98. $this->root = $this->getFullPath($this->root, $cwd);
  99. if (!empty($this->options['startPath'])) {
  100. $this->options['startPath'] = $this->getFullPath($this->options['startPath'], $this->root);
  101. }
  102. if (is_null($this->options['syncChkAsTs'])) {
  103. $this->options['syncChkAsTs'] = true;
  104. }
  105. if (is_null($this->options['syncCheckFunc'])) {
  106. $this->options['syncCheckFunc'] = array($this, 'localFileSystemInotify');
  107. }
  108. return true;
  109. }
  110. /**
  111. * Configure after successfull mount.
  112. *
  113. * @return void
  114. * @author Dmitry (dio) Levashov
  115. **/
  116. protected function configure() {
  117. $root = $this->stat($this->root);
  118. // chek thumbnails path
  119. if ($this->options['tmbPath']) {
  120. $this->options['tmbPath'] = strpos($this->options['tmbPath'], DIRECTORY_SEPARATOR) === false
  121. // tmb path set as dirname under root dir
  122. ? $this->_abspath($this->options['tmbPath'])
  123. // tmb path as full path
  124. : $this->_normpath($this->options['tmbPath']);
  125. }
  126. parent::configure();
  127. // set $this->tmp by options['tmpPath']
  128. $this->tmp = '';
  129. if (!empty($this->options['tmpPath'])) {
  130. if ((is_dir($this->options['tmpPath']) || mkdir($this->options['tmpPath'], 0755, true)) && is_writable($this->options['tmpPath'])) {
  131. $this->tmp = $this->options['tmpPath'];
  132. }
  133. }
  134. if (!$this->tmp && ($tmp = elFinder::getStaticVar('commonTempPath'))) {
  135. $this->tmp = $tmp;
  136. }
  137. // if no thumbnails url - try detect it
  138. if ($root['read'] && !$this->tmbURL && $this->URL) {
  139. if (strpos($this->tmbPath, $this->root) === 0) {
  140. $this->tmbURL = $this->URL.str_replace(DIRECTORY_SEPARATOR, '/', substr($this->tmbPath, strlen($this->root)+1));
  141. if (preg_match("|[^/?&=]$|", $this->tmbURL)) {
  142. $this->tmbURL .= '/';
  143. }
  144. }
  145. }
  146. // check quarantine dir
  147. $this->quarantine = '';
  148. if (!empty($this->options['quarantine'])) {
  149. if (is_dir($this->options['quarantine'])) {
  150. if (is_writable($this->options['quarantine'])) {
  151. $this->quarantine = $this->options['quarantine'];
  152. }
  153. $this->options['quarantine'] = '';
  154. } else {
  155. $this->quarantine = $this->_abspath($this->options['quarantine']);
  156. if ((!is_dir($this->quarantine) && !mkdir($this->quarantine)) || !is_writable($this->quarantine)) {
  157. $this->options['quarantine'] = $this->quarantine = '';
  158. }
  159. }
  160. }
  161. if (!$this->quarantine) {
  162. if (!$this->tmp) {
  163. $this->archivers['extract'] = array();
  164. $this->disabled[] = 'extract';
  165. } else {
  166. $this->quarantine = $this->tmp;
  167. }
  168. }
  169. if ($this->options['quarantine']) {
  170. $this->attributes[] = array(
  171. 'pattern' => '~^'.preg_quote(DIRECTORY_SEPARATOR.$this->options['quarantine']).'$~',
  172. 'read' => false,
  173. 'write' => false,
  174. 'locked' => true,
  175. 'hidden' => true
  176. );
  177. }
  178. if (! empty($this->options['keepTimestamp'])) {
  179. $this->options['keepTimestamp'] = array_flip($this->options['keepTimestamp']);
  180. }
  181. $this->statOwner = (!empty($this->options['statOwner']));
  182. }
  183. /**
  184. * Long pooling sync checker
  185. * This function require server command `inotifywait`
  186. * If `inotifywait` need full path, Please add `define('ELFINER_INOTIFYWAIT_PATH', '/PATH_TO/inotifywait');` into connector.php
  187. *
  188. * @param string $path
  189. * @param int $standby
  190. * @param number $compare
  191. * @return number|bool
  192. */
  193. public function localFileSystemInotify($path, $standby, $compare) {
  194. if (isset($this->sessionCache['localFileSystemInotify_disable'])) {
  195. return false;
  196. }
  197. $path = realpath($path);
  198. $mtime = filemtime($path);
  199. if (! $mtime) {
  200. return false;
  201. }
  202. if ($mtime != $compare) {
  203. return $mtime;
  204. }
  205. $inotifywait = defined('ELFINER_INOTIFYWAIT_PATH')? ELFINER_INOTIFYWAIT_PATH : 'inotifywait';
  206. $standby = max(1, intval($standby));
  207. $cmd = $inotifywait.' '.escapeshellarg($path).' -t '.$standby.' -e moved_to,moved_from,move,close_write,delete,delete_self';
  208. $this->procExec($cmd , $o, $r);
  209. if ($r === 0) {
  210. // changed
  211. clearstatcache();
  212. if (file_exists($path)) {
  213. $mtime = filemtime($path); // error on busy?
  214. return $mtime? $mtime : time();
  215. } else {
  216. // target was removed
  217. return 0;
  218. }
  219. } else if ($r === 2) {
  220. // not changed (timeout)
  221. return $compare;
  222. }
  223. // error
  224. // cache to $_SESSION
  225. $this->sessionCache['localFileSystemInotify_disable'] = true;
  226. $this->session->set($this->id, $this->sessionCache, true);
  227. return false;
  228. }
  229. /*********************************************************************/
  230. /* FS API */
  231. /*********************************************************************/
  232. /*********************** paths/urls *************************/
  233. /**
  234. * Return parent directory path
  235. *
  236. * @param string $path file path
  237. * @return string
  238. * @author Dmitry (dio) Levashov
  239. **/
  240. protected function _dirname($path) {
  241. return dirname($path);
  242. }
  243. /**
  244. * Return file name
  245. *
  246. * @param string $path file path
  247. * @return string
  248. * @author Dmitry (dio) Levashov
  249. **/
  250. protected function _basename($path) {
  251. return basename($path);
  252. }
  253. /**
  254. * Join dir name and file name and retur full path
  255. *
  256. * @param string $dir
  257. * @param string $name
  258. * @return string
  259. * @author Dmitry (dio) Levashov
  260. **/
  261. protected function _joinPath($dir, $name) {
  262. return rtrim($dir, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR . $name;
  263. }
  264. /**
  265. * Return normalized path, this works the same as os.path.normpath() in Python
  266. *
  267. * @param string $path path
  268. * @return string
  269. * @author Troex Nevelin
  270. **/
  271. protected function _normpath($path) {
  272. if (empty($path)) {
  273. return '.';
  274. }
  275. $changeSep = (DIRECTORY_SEPARATOR !== '/');
  276. if ($changeSep) {
  277. $drive = '';
  278. if (preg_match('/^([a-zA-Z]:)(.*)/', $path, $m)) {
  279. $drive = $m[1];
  280. $path = $m[2]? $m[2] : '/';
  281. }
  282. $path = str_replace(DIRECTORY_SEPARATOR, '/', $path);
  283. }
  284. if (strpos($path, '/') === 0) {
  285. $initial_slashes = true;
  286. } else {
  287. $initial_slashes = false;
  288. }
  289. if (($initial_slashes)
  290. && (strpos($path, '//') === 0)
  291. && (strpos($path, '///') === false)) {
  292. $initial_slashes = 2;
  293. }
  294. $initial_slashes = (int) $initial_slashes;
  295. $comps = explode('/', $path);
  296. $new_comps = array();
  297. foreach ($comps as $comp) {
  298. if (in_array($comp, array('', '.'))) {
  299. continue;
  300. }
  301. if (($comp != '..')
  302. || (!$initial_slashes && !$new_comps)
  303. || ($new_comps && (end($new_comps) == '..'))) {
  304. array_push($new_comps, $comp);
  305. } elseif ($new_comps) {
  306. array_pop($new_comps);
  307. }
  308. }
  309. $comps = $new_comps;
  310. $path = implode('/', $comps);
  311. if ($initial_slashes) {
  312. $path = str_repeat('/', $initial_slashes) . $path;
  313. }
  314. if ($changeSep) {
  315. $path = $drive . str_replace('/', DIRECTORY_SEPARATOR, $path);
  316. }
  317. return $path ? $path : '.';
  318. }
  319. /**
  320. * Return file path related to root dir
  321. *
  322. * @param string $path file path
  323. * @return string
  324. * @author Dmitry (dio) Levashov
  325. **/
  326. protected function _relpath($path) {
  327. if ($path === $this->root) {
  328. return '';
  329. } else {
  330. if (strpos($path, $this->root) === 0) {
  331. return ltrim(substr($path, strlen($this->root)), DIRECTORY_SEPARATOR);
  332. } else {
  333. // for link
  334. return $path;
  335. }
  336. }
  337. }
  338. /**
  339. * Convert path related to root dir into real path
  340. *
  341. * @param string $path file path
  342. * @return string
  343. * @author Dmitry (dio) Levashov
  344. **/
  345. protected function _abspath($path) {
  346. if ($path === DIRECTORY_SEPARATOR) {
  347. return $this->root;
  348. } else {
  349. if ($path[0] === DIRECTORY_SEPARATOR) {
  350. // for link
  351. return $path;
  352. } else {
  353. return $this->_joinPath($this->root, $path);
  354. }
  355. }
  356. }
  357. /**
  358. * Return fake path started from root dir
  359. *
  360. * @param string $path file path
  361. * @return string
  362. * @author Dmitry (dio) Levashov
  363. **/
  364. protected function _path($path) {
  365. return $this->rootName.($path == $this->root ? '' : $this->separator.$this->_relpath($path));
  366. }
  367. /**
  368. * Return true if $path is children of $parent
  369. *
  370. * @param string $path path to check
  371. * @param string $parent parent path
  372. * @return bool
  373. * @author Dmitry (dio) Levashov
  374. **/
  375. protected function _inpath($path, $parent) {
  376. $cwd = getcwd();
  377. $real_path = $this->getFullPath($path, $cwd);
  378. $real_parent = $this->getFullPath($parent, $cwd);
  379. if ($real_path && $real_parent) {
  380. return $real_path === $real_parent || strpos($real_path, rtrim($real_parent, DIRECTORY_SEPARATOR).DIRECTORY_SEPARATOR) === 0;
  381. }
  382. return false;
  383. }
  384. /***************** file stat ********************/
  385. /**
  386. * Return stat for given path.
  387. * Stat contains following fields:
  388. * - (int) size file size in b. required
  389. * - (int) ts file modification time in unix time. required
  390. * - (string) mime mimetype. required for folders, others - optionally
  391. * - (bool) read read permissions. required
  392. * - (bool) write write permissions. required
  393. * - (bool) locked is object locked. optionally
  394. * - (bool) hidden is object hidden. optionally
  395. * - (string) alias for symlinks - link target path relative to root path. optionally
  396. * - (string) target for symlinks - link target path. optionally
  397. *
  398. * If file does not exists - returns empty array or false.
  399. *
  400. * @param string $path file path
  401. * @return array|false
  402. * @author Dmitry (dio) Levashov
  403. **/
  404. protected function _stat($path) {
  405. $stat = array();
  406. if (!file_exists($path) && !is_link($path)) {
  407. return $stat;
  408. }
  409. //Verifies the given path is the root or is inside the root. Prevents directory traveral.
  410. if (!$this->_inpath($path, $this->root)) {
  411. return $stat;
  412. }
  413. $gid = $uid = 0;
  414. $stat['isowner'] = false;
  415. $linkreadable = false;
  416. if ($path != $this->root && is_link($path)) {
  417. if (! $this->options['followSymLinks']) {
  418. return array();
  419. }
  420. if (!($target = $this->readlink($path))
  421. || $target == $path) {
  422. if (is_null($target)) {
  423. $stat = array();
  424. return $stat;
  425. } else {
  426. $stat['mime'] = 'symlink-broken';
  427. $target = readlink($path);
  428. $lstat = lstat($path);
  429. $ostat = $this->getOwnerStat($lstat['uid'], $lstat['gid']);
  430. $linkreadable = !empty($ostat['isowner']);
  431. }
  432. }
  433. $stat['alias'] = $this->_path($target);
  434. $stat['target'] = $target;
  435. }
  436. $readable = is_readable($path);
  437. if ($readable) {
  438. $size = sprintf('%u', filesize($path));
  439. $stat['ts'] = filemtime($path);
  440. if ($this->statOwner) {
  441. $fstat = stat($path);
  442. $uid = $fstat['uid'];
  443. $gid = $fstat['gid'];
  444. $stat['perm'] = substr((string)decoct($fstat['mode']), -4);
  445. $stat = array_merge($stat, $this->getOwnerStat($uid, $gid));
  446. }
  447. }
  448. if (($dir = is_dir($path)) && $this->options['detectDirIcon']) {
  449. $favicon = $path . DIRECTORY_SEPARATOR . $this->options['detectDirIcon'];
  450. if ($this->URL && file_exists($favicon)) {
  451. $stat['icon'] = $this->URL . str_replace(DIRECTORY_SEPARATOR, '/', substr($favicon, strlen($this->root) + 1));
  452. }
  453. }
  454. if (!isset($stat['mime'])) {
  455. $stat['mime'] = $dir ? 'directory' : $this->mimetype($path);
  456. }
  457. //logical rights first
  458. $stat['read'] = ($linkreadable || $readable)? null : false;
  459. $stat['write'] = is_writable($path)? null : false;
  460. if (is_null($stat['read'])) {
  461. if ($dir) {
  462. $stat['size'] = 0;
  463. } else if (isset($size)) {
  464. $stat['size'] = $size;
  465. }
  466. }
  467. return $stat;
  468. }
  469. /**
  470. * Get stat `owner`, `group` and `isowner` by `uid` and `gid`
  471. * Sub-fuction of _stat() and _scandir()
  472. *
  473. * @param integer $uid
  474. * @param integer $gid
  475. * @return array stat
  476. */
  477. protected function getOwnerStat($uid, $gid) {
  478. static $names = null;
  479. static $phpuid = null;
  480. if (is_null($names)) {
  481. $names = array('uid' => array(), 'gid' =>array());
  482. }
  483. if (is_null($phpuid)) {
  484. if (is_callable('posix_getuid')) {
  485. $phpuid = posix_getuid();
  486. } else {
  487. $phpuid = 0;
  488. }
  489. }
  490. $stat = array();
  491. if ($uid) {
  492. $stat['isowner'] = ($phpuid == $uid);
  493. if (isset($names['uid'][$uid])) {
  494. $stat['owner'] = $names['uid'][$uid];
  495. } else if (is_callable('posix_getpwuid')) {
  496. $pwuid = posix_getpwuid($uid);
  497. $stat['owner'] = $names['uid'][$uid] = $pwuid['name'];
  498. } else {
  499. $stat['owner'] = $names['uid'][$uid] = $uid;
  500. }
  501. }
  502. if ($gid) {
  503. if (isset($names['gid'][$gid])) {
  504. $stat['group'] = $names['gid'][$gid];
  505. } else if (is_callable('posix_getgrgid')) {
  506. $grgid = posix_getgrgid($gid);
  507. $stat['group'] = $names['gid'][$gid] = $grgid['name'];
  508. } else {
  509. $stat['group'] = $names['gid'][$gid] = $gid;
  510. }
  511. }
  512. return $stat;
  513. }
  514. /**
  515. * Return true if path is dir and has at least one childs directory
  516. *
  517. * @param string $path dir path
  518. * @return bool
  519. * @author Dmitry (dio) Levashov
  520. **/
  521. protected function _subdirs($path) {
  522. $dirs = false;
  523. if (is_dir($path) && is_readable($path)) {
  524. if (class_exists('FilesystemIterator', false)) {
  525. $dirItr = new ParentIterator(
  526. new RecursiveDirectoryIterator($path,
  527. FilesystemIterator::SKIP_DOTS |
  528. FilesystemIterator::CURRENT_AS_SELF |
  529. (defined('RecursiveDirectoryIterator::FOLLOW_SYMLINKS')?
  530. RecursiveDirectoryIterator::FOLLOW_SYMLINKS : 0)
  531. )
  532. );
  533. $dirItr->rewind();
  534. if ($dirItr->hasChildren()) {
  535. $dirs = true;
  536. $name = $dirItr->getSubPathName();
  537. while($dirItr->valid()) {
  538. if (!$this->attr($path . DIRECTORY_SEPARATOR . $name, 'read', null, true)) {
  539. $dirs = false;
  540. $dirItr->next();
  541. $name = $dirItr->getSubPathName();
  542. continue;
  543. }
  544. $dirs = true;
  545. break;
  546. }
  547. }
  548. } else {
  549. $path = strtr($path, array('[' => '\\[', ']' => '\\]', '*' => '\\*', '?' => '\\?'));
  550. return (bool)glob(rtrim($path, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR . '*', GLOB_ONLYDIR);
  551. }
  552. }
  553. return $dirs;
  554. }
  555. /**
  556. * Return object width and height
  557. * Usualy used for images, but can be realize for video etc...
  558. *
  559. * @param string $path file path
  560. * @param string $mime file mime type
  561. * @return string
  562. * @author Dmitry (dio) Levashov
  563. **/
  564. protected function _dimensions($path, $mime) {
  565. clearstatcache();
  566. return strpos($mime, 'image') === 0 && is_readable($path) && ($s = getimagesize($path)) !== false
  567. ? $s[0].'x'.$s[1]
  568. : false;
  569. }
  570. /******************** file/dir content *********************/
  571. /**
  572. * Return symlink target file
  573. *
  574. * @param string $path link path
  575. * @return string
  576. * @author Dmitry (dio) Levashov
  577. **/
  578. protected function readlink($path) {
  579. if (!($target = readlink($path))) {
  580. return null;
  581. }
  582. if (strpos($target, $this->systemRoot) !== 0) {
  583. $target = $this->_joinPath(dirname($path), $target);
  584. }
  585. if (!file_exists($target)) {
  586. return false;
  587. }
  588. return $target;
  589. }
  590. /**
  591. * Return files list in directory.
  592. *
  593. * @param string $path dir path
  594. * @return array
  595. * @author Dmitry (dio) Levashov
  596. **/
  597. protected function _scandir($path) {
  598. elFinder::checkAborted();
  599. $files = array();
  600. $cache = array();
  601. $dirWritable = is_writable($path);
  602. $dirItr = array();
  603. $followSymLinks = $this->options['followSymLinks'];
  604. try {
  605. $dirItr = new DirectoryIterator($path);
  606. } catch (UnexpectedValueException $e) {}
  607. foreach ($dirItr as $file) {
  608. try {
  609. if ($file->isDot()) { continue; }
  610. $files[] = $fpath = $file->getPathname();
  611. $br = false;
  612. $stat = array();
  613. $gid = $uid = 0;
  614. $stat['isowner'] = false;
  615. $linkreadable = false;
  616. if ($file->isLink()) {
  617. if (! $followSymLinks) { continue; }
  618. if (!($target = $this->readlink($fpath))
  619. || $target == $fpath) {
  620. if (is_null($target)) {
  621. $stat = array();
  622. $br = true;
  623. } else {
  624. $_path = $fpath;
  625. $stat['mime'] = 'symlink-broken';
  626. $target = readlink($_path);
  627. $lstat = lstat($_path);
  628. $ostat = $this->getOwnerStat($lstat['uid'], $lstat['gid']);
  629. $linkreadable = !empty($ostat['isowner']);
  630. $dir = false;
  631. $stat['alias'] = $this->_path($target);
  632. $stat['target'] = $target;
  633. }
  634. } else {
  635. $dir = is_dir($target);
  636. $stat['alias'] = $this->_path($target);
  637. $stat['target'] = $target;
  638. $stat['mime'] = $dir ? 'directory' : $this->mimetype($stat['alias']);
  639. }
  640. } else {
  641. if (($dir = $file->isDir()) && $this->options['detectDirIcon']) {
  642. $path = $file->getPathname();
  643. $favicon = $path . DIRECTORY_SEPARATOR . $this->options['detectDirIcon'];
  644. if ($this->URL && file_exists($favicon)) {
  645. $stat['icon'] = $this->URL . str_replace(DIRECTORY_SEPARATOR, '/', substr($favicon, strlen($this->root) + 1));
  646. }
  647. }
  648. $stat['mime'] = $dir ? 'directory' : $this->mimetype($fpath);
  649. }
  650. $size = sprintf('%u', $file->getSize());
  651. $stat['ts'] = $file->getMTime();
  652. if (!$br) {
  653. if ($this->statOwner && !$linkreadable) {
  654. $uid = $file->getOwner();
  655. $gid = $file->getGroup();
  656. $stat['perm'] = substr((string)decoct($file->getPerms()), -4);
  657. $stat = array_merge($stat, $this->getOwnerStat($uid, $gid));
  658. }
  659. //logical rights first
  660. $stat['read'] = ($linkreadable || $file->isReadable())? null : false;
  661. $stat['write'] = $file->isWritable()? null : false;
  662. $stat['locked'] = $dirWritable? null : true;
  663. if (is_null($stat['read'])) {
  664. $stat['size'] = $dir ? 0 : $size;
  665. }
  666. }
  667. $cache[] = array($fpath, $stat);
  668. } catch (RuntimeException $e) {
  669. continue;
  670. }
  671. }
  672. if ($cache) {
  673. $cache = $this->convEncOut($cache, false);
  674. foreach($cache as $d) {
  675. $this->updateCache($d[0], $d[1]);
  676. }
  677. }
  678. return $files;
  679. }
  680. /**
  681. * Open file and return file pointer
  682. *
  683. * @param string $path file path
  684. * @param string $mode
  685. * @return false|resource
  686. * @internal param bool $write open file for writing
  687. * @author Dmitry (dio) Levashov
  688. */
  689. protected function _fopen($path, $mode='rb') {
  690. return fopen($path, $mode);
  691. }
  692. /**
  693. * Close opened file
  694. *
  695. * @param resource $fp file pointer
  696. * @param string $path
  697. * @return bool
  698. * @author Dmitry (dio) Levashov
  699. */
  700. protected function _fclose($fp, $path='') {
  701. return (is_resource($fp) && fclose($fp));
  702. }
  703. /******************** file/dir manipulations *************************/
  704. /**
  705. * Create dir and return created dir path or false on failed
  706. *
  707. * @param string $path parent dir path
  708. * @param string $name new directory name
  709. * @return string|bool
  710. * @author Dmitry (dio) Levashov
  711. **/
  712. protected function _mkdir($path, $name) {
  713. $path = $this->_joinPath($path, $name);
  714. if (mkdir($path)) {
  715. chmod($path, $this->options['dirMode']);
  716. return $path;
  717. }
  718. return false;
  719. }
  720. /**
  721. * Create file and return it's path or false on failed
  722. *
  723. * @param string $path parent dir path
  724. * @param string $name new file name
  725. * @return string|bool
  726. * @author Dmitry (dio) Levashov
  727. **/
  728. protected function _mkfile($path, $name) {
  729. $path = $this->_joinPath($path, $name);
  730. if (($fp = fopen($path, 'w'))) {
  731. fclose($fp);
  732. chmod($path, $this->options['fileMode']);
  733. return $path;
  734. }
  735. return false;
  736. }
  737. /**
  738. * Create symlink
  739. *
  740. * @param string $source file to link to
  741. * @param string $targetDir folder to create link in
  742. * @param string $name symlink name
  743. * @return bool
  744. * @author Dmitry (dio) Levashov
  745. **/
  746. protected function _symlink($source, $targetDir, $name) {
  747. return symlink($source, $this->_joinPath($targetDir, $name));
  748. }
  749. /**
  750. * Copy file into another file
  751. *
  752. * @param string $source source file path
  753. * @param string $targetDir target directory path
  754. * @param string $name new file name
  755. * @return bool
  756. * @author Dmitry (dio) Levashov
  757. **/
  758. protected function _copy($source, $targetDir, $name) {
  759. $mtime = filemtime($source);
  760. $target = $this->_joinPath($targetDir, $name);
  761. if ($ret = copy($source, $target)) {
  762. isset($this->options['keepTimestamp']['copy']) && $mtime && touch($target, $mtime);
  763. }
  764. return $ret;
  765. }
  766. /**
  767. * Move file into another parent dir.
  768. * Return new file path or false.
  769. *
  770. * @param string $source source file path
  771. * @param $targetDir
  772. * @param string $name file name
  773. * @return bool|string
  774. * @internal param string $target target dir path
  775. * @author Dmitry (dio) Levashov
  776. */
  777. protected function _move($source, $targetDir, $name) {
  778. $mtime = filemtime($source);
  779. $target = $this->_joinPath($targetDir, $name);
  780. if ($ret = rename($source, $target) ? $target : false) {
  781. isset($this->options['keepTimestamp']['move']) && $mtime && touch($target, $mtime);
  782. }
  783. return $ret;
  784. }
  785. /**
  786. * Remove file
  787. *
  788. * @param string $path file path
  789. * @return bool
  790. * @author Dmitry (dio) Levashov
  791. **/
  792. protected function _unlink($path) {
  793. return is_file($path) && unlink($path);
  794. }
  795. /**
  796. * Remove dir
  797. *
  798. * @param string $path dir path
  799. * @return bool
  800. * @author Dmitry (dio) Levashov
  801. **/
  802. protected function _rmdir($path) {
  803. return rmdir($path);
  804. }
  805. /**
  806. * Create new file and write into it from file pointer.
  807. * Return new file path or false on error.
  808. *
  809. * @param resource $fp file pointer
  810. * @param string $dir target dir path
  811. * @param string $name file name
  812. * @param array $stat file stat (required by some virtual fs)
  813. * @return bool|string
  814. * @author Dmitry (dio) Levashov
  815. **/
  816. protected function _save($fp, $dir, $name, $stat) {
  817. $path = $this->_joinPath($dir, $name);
  818. $meta = stream_get_meta_data($fp);
  819. $uri = isset($meta['uri'])? $meta['uri'] : '';
  820. if ($uri && ! preg_match('#^[a-zA-Z0-9]+://#', $uri) && !is_link($uri)) {
  821. fclose($fp);
  822. $mtime = filemtime($uri);
  823. $isCmdPaste = ($this->ARGS['cmd'] === 'paste');
  824. $isCmdCopy = ($isCmdPaste && empty($this->ARGS['cut']));
  825. if (($isCmdCopy || !rename($uri, $path)) && !copy($uri, $path)) {
  826. return false;
  827. }
  828. // keep timestamp on upload
  829. if ($mtime && $this->ARGS['cmd'] === 'upload') {
  830. touch($path, isset($this->options['keepTimestamp']['upload'])? $mtime : time());
  831. }
  832. } else {
  833. if (file_put_contents($path, $fp, LOCK_EX) === false) {
  834. return false;
  835. }
  836. }
  837. chmod($path, $this->options['fileMode']);
  838. return $path;
  839. }
  840. /**
  841. * Get file contents
  842. *
  843. * @param string $path file path
  844. * @return string|false
  845. * @author Dmitry (dio) Levashov
  846. **/
  847. protected function _getContents($path) {
  848. return file_get_contents($path);
  849. }
  850. /**
  851. * Write a string to a file
  852. *
  853. * @param string $path file path
  854. * @param string $content new file content
  855. * @return bool
  856. * @author Dmitry (dio) Levashov
  857. **/
  858. protected function _filePutContents($path, $content) {
  859. return (file_put_contents($path, $content, LOCK_EX) !== false);
  860. }
  861. /**
  862. * Detect available archivers
  863. *
  864. * @return void
  865. **/
  866. protected function _checkArchivers() {
  867. $this->archivers = $this->getArchivers();
  868. return;
  869. }
  870. /**
  871. * chmod availability
  872. *
  873. * @param string $path
  874. * @param string $mode
  875. * @return bool
  876. */
  877. protected function _chmod($path, $mode) {
  878. $modeOct = is_string($mode) ? octdec($mode) : octdec(sprintf("%04o",$mode));
  879. return chmod($path, $modeOct);
  880. }
  881. /**
  882. * Recursive symlinks search
  883. *
  884. * @param string $path file/dir path
  885. * @return bool
  886. * @author Dmitry (dio) Levashov
  887. **/
  888. protected function _findSymlinks($path) {
  889. return self::localFindSymlinks($path);
  890. }
  891. /**
  892. * Extract files from archive
  893. *
  894. * @param string $path archive path
  895. * @param array $arc archiver command and arguments (same as in $this->archivers)
  896. * @return true
  897. * @author Dmitry (dio) Levashov,
  898. * @author Alexey Sukhotin
  899. **/
  900. protected function _extract($path, $arc) {
  901. if ($this->quarantine) {
  902. $dir = $this->quarantine.DIRECTORY_SEPARATOR.md5(basename($path).mt_rand());
  903. $archive = (isset($arc['toSpec']) || $arc['cmd'] === 'phpfunction')? '' : $dir.DIRECTORY_SEPARATOR.basename($path);
  904. if (!mkdir($dir)) {
  905. return false;
  906. }
  907. // insurance unexpected shutdown
  908. register_shutdown_function(array($this, 'rmdirRecursive'), realpath($dir));
  909. chmod($dir, 0777);
  910. // copy in quarantine
  911. if (!is_readable($path) || ($archive && !copy($path, $archive))) {
  912. return false;
  913. }
  914. // extract in quarantine
  915. $this->unpackArchive($path, $arc, $archive? true : $dir);
  916. // get files list
  917. $ls = self::localScandir($dir);
  918. // no files - extract error ?
  919. if (empty($ls)) {
  920. return false;
  921. }
  922. $this->archiveSize = 0;
  923. // find symlinks and check extracted items
  924. $checkRes = $this->checkExtractItems($dir);
  925. if ($checkRes['symlinks']) {
  926. self::localRmdirRecursive($dir);
  927. return $this->setError(array_merge($this->error, array(elFinder::ERROR_ARC_SYMLINKS)));
  928. }
  929. $this->archiveSize = $checkRes['totalSize'];
  930. if ($checkRes['rmNames']) {
  931. foreach($checkRes['rmNames'] as $name) {
  932. $this->addError(elFinder::ERROR_SAVE, $name);
  933. }
  934. }
  935. // check max files size
  936. if ($this->options['maxArcFilesSize'] > 0 && $this->options['maxArcFilesSize'] < $this->archiveSize) {
  937. $this->delTree($dir);
  938. return $this->setError(elFinder::ERROR_ARC_MAXSIZE);
  939. }
  940. $extractTo = $this->extractToNewdir; // 'auto', ture or false
  941. // archive contains one item - extract in archive dir
  942. $name = '';
  943. $src = $dir.DIRECTORY_SEPARATOR.$ls[0];
  944. if (($extractTo === 'auto' || !$extractTo) && count($ls) === 1 && is_file($src)) {
  945. $name = $ls[0];
  946. } else if ($extractTo === 'auto' || $extractTo) {
  947. // for several files - create new directory
  948. // create unique name for directory
  949. $src = $dir;
  950. $splits = elFinder::splitFileExtention(basename($path));
  951. $name = $splits[0];
  952. $test = dirname($path).DIRECTORY_SEPARATOR.$name;
  953. if (file_exists($test) || is_link($test)) {
  954. $name = $this->uniqueName(dirname($path), $name, '-', false);
  955. }
  956. }
  957. if ($name !== '') {
  958. $result = dirname($path).DIRECTORY_SEPARATOR.$name;
  959. if (! rename($src, $result)) {
  960. $this->delTree($dir);
  961. return false;
  962. }
  963. } else {
  964. $dstDir = dirname($path);
  965. $result = array();
  966. foreach($ls as $name) {
  967. $target = $dstDir.DIRECTORY_SEPARATOR.$name;
  968. if (self::localMoveRecursive($dir.DIRECTORY_SEPARATOR.$name, $target, true, $this->options['copyJoin'])) {
  969. $result[] = $target;
  970. }
  971. }
  972. if (!$result) {
  973. $this->delTree($dir);
  974. return false;
  975. }
  976. }
  977. is_dir($dir) && $this->delTree($dir);
  978. return (is_array($result) || file_exists($result)) ? $result : false;
  979. }
  980. //TODO: Add return statement here
  981. }
  982. /**
  983. * Create archive and return its path
  984. *
  985. * @param string $dir target dir
  986. * @param array $files files names list
  987. * @param string $name archive name
  988. * @param array $arc archiver options
  989. * @return string|bool
  990. * @author Dmitry (dio) Levashov,
  991. * @author Alexey Sukhotin
  992. **/
  993. protected function _archive($dir, $files, $name, $arc) {
  994. return $this->makeArchive($dir, $files, $name, $arc);
  995. }
  996. /******************** Over write functions *************************/
  997. /**
  998. * File path of local server side work file path
  999. *
  1000. * @param string $path
  1001. * @return string
  1002. * @author Naoki Sawada
  1003. */
  1004. protected function getWorkFile($path) {
  1005. return $path;
  1006. }
  1007. /**
  1008. * Delete dirctory trees
  1009. *
  1010. * @param string $localpath path need convert encoding to server encoding
  1011. * @return boolean
  1012. * @author Naoki Sawada
  1013. */
  1014. protected function delTree($localpath) {
  1015. return $this->rmdirRecursive($localpath);
  1016. }
  1017. /**
  1018. * Return fileinfo based on filename
  1019. * For item ID based path file system
  1020. * Please override if needed on each drivers
  1021. *
  1022. * @param string $path file cache
  1023. * @return array
  1024. */
  1025. protected function isNameExists($path) {
  1026. $exists = file_exists($this->convEncIn($path));
  1027. // restore locale
  1028. $this->convEncOut();
  1029. return $exists? $this->stat($path) : false;
  1030. }
  1031. /******************** Over write (Optimized) functions *************************/
  1032. /**
  1033. * Recursive files search
  1034. *
  1035. * @param string $path dir path
  1036. * @param string $q search string
  1037. * @param array $mimes
  1038. * @return array
  1039. * @author Dmitry (dio) Levashov
  1040. * @author Naoki Sawada
  1041. **/
  1042. protected function doSearch($path, $q, $mimes) {
  1043. if ($this->encoding || ! class_exists('FilesystemIterator', false)) {
  1044. // non UTF-8 use elFinderVolumeDriver::doSearch()
  1045. return parent::doSearch($path, $q, $mimes);
  1046. }
  1047. $result = array();
  1048. $timeout = $this->options['searchTimeout']? $this->searchStart + $this->options['searchTimeout'] : 0;
  1049. if ($timeout && $timeout < time()) {
  1050. $this->setError(elFinder::ERROR_SEARCH_TIMEOUT, $this->path($this->encode($path)));
  1051. return $result;
  1052. }
  1053. elFinder::extendTimeLimit($this->options['searchTimeout'] + 30);
  1054. $match = array();
  1055. try {
  1056. $iterator = new RecursiveIteratorIterator(
  1057. new RecursiveCallbackFilterIterator(
  1058. new RecursiveDirectoryIterator($path,
  1059. FilesystemIterator::KEY_AS_PATHNAME |
  1060. FilesystemIterator::SKIP_DOTS |
  1061. ((defined('RecursiveDirectoryIterator::FOLLOW_SYMLINKS') && $this->options['followSymLinks'])?
  1062. RecursiveDirectoryIterator::FOLLOW_SYMLINKS : 0)
  1063. ),
  1064. array($this, 'localFileSystemSearchIteratorFilter')
  1065. ),
  1066. RecursiveIteratorIterator::SELF_FIRST,
  1067. RecursiveIteratorIterator::CATCH_GET_CHILD
  1068. );
  1069. foreach ($iterator as $key => $node) {
  1070. if ($timeout && ($this->error || $timeout < time())) {
  1071. !$this->error && $this->setError(elFinder::ERROR_SEARCH_TIMEOUT, $this->path($this->encode($node->getPath)));
  1072. break;
  1073. }
  1074. if ($node->isDir()) {
  1075. if ($this->stripos($node->getFilename(), $q) !== false) {
  1076. $match[] = $key;
  1077. }
  1078. } else {
  1079. $match[] = $key;
  1080. }
  1081. }
  1082. } catch (Exception $e) {}
  1083. if ($match) {
  1084. foreach($match as $p) {
  1085. if ($timeout && ($this->error || $timeout < time())) {
  1086. !$this->error && $this->setError(elFinder::ERROR_SEARCH_TIMEOUT, $this->path($this->encode(dirname($p))));
  1087. break;
  1088. }
  1089. $stat = $this->stat($p);
  1090. if (!$stat) { // invalid links
  1091. continue;
  1092. }
  1093. if (!empty($stat['hidden']) || !$this->mimeAccepted($stat['mime'], $mimes)) {
  1094. continue;
  1095. }
  1096. $name = $stat['name'];
  1097. if ((!$mimes || $stat['mime'] !== 'directory')) {
  1098. $stat['path'] = $this->path($stat['hash']);
  1099. if ($this->URL && !isset($stat['url'])) {
  1100. $_path = str_replace(DIRECTORY_SEPARATOR, '/', substr($p, strlen($this->root) + 1));
  1101. $stat['url'] = $this->URL . str_replace('%2F', '/', rawurlencode($_path));
  1102. }
  1103. $result[] = $stat;
  1104. }
  1105. }
  1106. }
  1107. return $result;
  1108. }
  1109. /******************** Original local functions ************************
  1110. * @param $file
  1111. * @param $key
  1112. * @param $iterator
  1113. * @return bool
  1114. */
  1115. public function localFileSystemSearchIteratorFilter($file, $key, $iterator) {
  1116. $name = $file->getFilename();
  1117. if ($this->doSearchCurrentQuery['excludes']) {
  1118. foreach($this->doSearchCurrentQuery['excludes'] as $exclude) {
  1119. if ($this->stripos($name, $exclude) !== false) {
  1120. return false;
  1121. }
  1122. }
  1123. }
  1124. if ($iterator->hasChildren()) {
  1125. if ($this->options['searchExDirReg'] && preg_match($this->options['searchExDirReg'], $key)) {
  1126. return false;
  1127. }
  1128. return (bool)$this->attr($key, 'read', null, true);
  1129. }
  1130. return ($this->stripos($name, $this->doSearchCurrentQuery['q']) === false)? false : true;
  1131. }
  1132. } // END class