elFinderVolumeLocalFileSystem.class.php 44 KB

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