elFinderVolumeLocalFileSystem.class.php 35 KB

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