elFinderVolumeFTP.class.php 57 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810
  1. <?php
  2. /**
  3. * Simple elFinder driver for FTP
  4. *
  5. * @author Dmitry (dio) Levashov
  6. * @author Cem (discofever)
  7. **/
  8. class elFinderVolumeFTP extends elFinderVolumeDriver
  9. {
  10. /**
  11. * Driver id
  12. * Must be started from letter and contains [a-z0-9]
  13. * Used as part of volume id
  14. *
  15. * @var string
  16. **/
  17. protected $driverId = 'f';
  18. /**
  19. * FTP Connection Instance
  20. *
  21. * @var resource a FTP stream
  22. **/
  23. protected $connect = null;
  24. /**
  25. * Directory for tmp files
  26. * If not set driver will try to use tmbDir as tmpDir
  27. *
  28. * @var string
  29. **/
  30. protected $tmpPath = '';
  31. /**
  32. * Last FTP error message
  33. *
  34. * @var string
  35. **/
  36. protected $ftpError = '';
  37. /**
  38. * FTP server output list as ftp on linux
  39. *
  40. * @var bool
  41. **/
  42. protected $ftpOsUnix;
  43. /**
  44. * FTP LIST command option
  45. *
  46. * @var string
  47. */
  48. protected $ftpListOption = '-al';
  49. /**
  50. * Is connected server Pure FTPd?
  51. *
  52. * @var bool
  53. */
  54. protected $isPureFtpd = false;
  55. /**
  56. * Is connected server with FTPS?
  57. *
  58. * @var bool
  59. */
  60. protected $isFTPS = false;
  61. /**
  62. * Tmp folder path
  63. *
  64. * @var string
  65. **/
  66. protected $tmp = '';
  67. /**
  68. * FTP command `MLST` support
  69. *
  70. * @var bool
  71. */
  72. private $MLSTsupprt = false;
  73. /**
  74. * Calling cacheDir() target path with non-MLST
  75. *
  76. * @var string
  77. */
  78. private $cacheDirTarget = '';
  79. /**
  80. * Constructor
  81. * Extend options with required fields
  82. *
  83. * @author Dmitry (dio) Levashov
  84. * @author Cem (DiscoFever)
  85. */
  86. public function __construct()
  87. {
  88. $opts = array(
  89. 'host' => 'localhost',
  90. 'user' => '',
  91. 'pass' => '',
  92. 'port' => 21,
  93. 'mode' => 'passive',
  94. 'ssl' => false,
  95. 'path' => '/',
  96. 'timeout' => 20,
  97. 'owner' => true,
  98. 'tmbPath' => '',
  99. 'tmpPath' => '',
  100. 'separator' => '/',
  101. 'checkSubfolders' => -1,
  102. 'dirMode' => 0755,
  103. 'fileMode' => 0644,
  104. 'rootCssClass' => 'elfinder-navbar-root-ftp',
  105. 'ftpListOption' => '-al',
  106. );
  107. $this->options = array_merge($this->options, $opts);
  108. $this->options['mimeDetect'] = 'internal';
  109. }
  110. /**
  111. * Prepare
  112. * Call from elFinder::netmout() before volume->mount()
  113. *
  114. * @param $options
  115. *
  116. * @return array volume root options
  117. * @author Naoki Sawada
  118. */
  119. public function netmountPrepare($options)
  120. {
  121. if (!empty($_REQUEST['encoding']) && iconv('UTF-8', $_REQUEST['encoding'], '') !== false) {
  122. $options['encoding'] = $_REQUEST['encoding'];
  123. if (!empty($_REQUEST['locale']) && setlocale(LC_ALL, $_REQUEST['locale'])) {
  124. setlocale(LC_ALL, elFinder::$locale);
  125. $options['locale'] = $_REQUEST['locale'];
  126. }
  127. }
  128. if (!empty($_REQUEST['FTPS'])) {
  129. $options['ssl'] = true;
  130. }
  131. $options['statOwner'] = true;
  132. $options['allowChmodReadOnly'] = true;
  133. $options['acceptedName'] = '#^[^/\\?*:|"<>]*[^./\\?*:|"<>]$#';
  134. return $options;
  135. }
  136. /*********************************************************************/
  137. /* INIT AND CONFIGURE */
  138. /*********************************************************************/
  139. /**
  140. * Prepare FTP connection
  141. * Connect to remote server and check if credentials are correct, if so, store the connection id in $ftp_conn
  142. *
  143. * @return bool
  144. * @author Dmitry (dio) Levashov
  145. * @author Cem (DiscoFever)
  146. **/
  147. protected function init()
  148. {
  149. if (!$this->options['host']
  150. || !$this->options['port']) {
  151. return $this->setError('Required options undefined.');
  152. }
  153. if (!$this->options['user']) {
  154. $this->options['user'] = 'anonymous';
  155. $this->options['pass'] = '';
  156. }
  157. if (!$this->options['path']) {
  158. $this->options['path'] = '/';
  159. }
  160. // make ney mount key
  161. $this->netMountKey = md5(join('-', array('ftp', $this->options['host'], $this->options['port'], $this->options['path'], $this->options['user'])));
  162. if (!function_exists('ftp_connect')) {
  163. return $this->setError('FTP extension not loaded.');
  164. }
  165. // remove protocol from host
  166. $scheme = parse_url($this->options['host'], PHP_URL_SCHEME);
  167. if ($scheme) {
  168. $this->options['host'] = substr($this->options['host'], strlen($scheme) + 3);
  169. }
  170. // normalize root path
  171. $this->root = $this->options['path'] = $this->_normpath($this->options['path']);
  172. if (empty($this->options['alias'])) {
  173. $this->options['alias'] = $this->options['user'] . '@' . $this->options['host'];
  174. if (!empty($this->options['netkey'])) {
  175. elFinder::$instance->updateNetVolumeOption($this->options['netkey'], 'alias', $this->options['alias']);
  176. }
  177. }
  178. $this->rootName = $this->options['alias'];
  179. $this->options['separator'] = '/';
  180. if (is_null($this->options['syncChkAsTs'])) {
  181. $this->options['syncChkAsTs'] = true;
  182. }
  183. if (isset($this->options['ftpListOption'])) {
  184. $this->ftpListOption = $this->options['ftpListOption'];
  185. }
  186. return $this->needOnline? $this->connect() : true;
  187. }
  188. /**
  189. * Configure after successfull mount.
  190. *
  191. * @return void
  192. * @throws elFinderAbortException
  193. * @author Dmitry (dio) Levashov
  194. */
  195. protected function configure()
  196. {
  197. parent::configure();
  198. if (!empty($this->options['tmpPath'])) {
  199. if ((is_dir($this->options['tmpPath']) || mkdir($this->options['tmpPath'], 0755, true)) && is_writable($this->options['tmpPath'])) {
  200. $this->tmp = $this->options['tmpPath'];
  201. }
  202. }
  203. if (!$this->tmp && ($tmp = elFinder::getStaticVar('commonTempPath'))) {
  204. $this->tmp = $tmp;
  205. }
  206. // fallback of $this->tmp
  207. if (!$this->tmp && $this->tmbPathWritable) {
  208. $this->tmp = $this->tmbPath;
  209. }
  210. if (!$this->tmp) {
  211. $this->disabled[] = 'mkfile';
  212. $this->disabled[] = 'paste';
  213. $this->disabled[] = 'duplicate';
  214. $this->disabled[] = 'upload';
  215. $this->disabled[] = 'edit';
  216. $this->disabled[] = 'archive';
  217. $this->disabled[] = 'extract';
  218. }
  219. // echo $this->tmp;
  220. }
  221. /**
  222. * Connect to ftp server
  223. *
  224. * @return bool
  225. * @author Dmitry (dio) Levashov
  226. **/
  227. protected function connect()
  228. {
  229. $withSSL = empty($this->options['ssl']) ? '' : ' with SSL';
  230. if ($withSSL) {
  231. if (!function_exists('ftp_ssl_connect') || !($this->connect = ftp_ssl_connect($this->options['host'], $this->options['port'], $this->options['timeout']))) {
  232. return $this->setError('Unable to connect to FTP server ' . $this->options['host'] . $withSSL);
  233. }
  234. $this->isFTPS = true;
  235. } else {
  236. if (!($this->connect = ftp_connect($this->options['host'], $this->options['port'], $this->options['timeout']))) {
  237. return $this->setError('Unable to connect to FTP server ' . $this->options['host']);
  238. }
  239. }
  240. if (!ftp_login($this->connect, $this->options['user'], $this->options['pass'])) {
  241. $this->umount();
  242. return $this->setError('Unable to login into ' . $this->options['host'] . $withSSL);
  243. }
  244. // try switch utf8 mode
  245. if ($this->encoding) {
  246. ftp_raw($this->connect, 'OPTS UTF8 OFF');
  247. } else {
  248. ftp_raw($this->connect, 'OPTS UTF8 ON');
  249. }
  250. $help = ftp_raw($this->connect, 'HELP');
  251. $this->isPureFtpd = stripos(implode(' ', $help), 'Pure-FTPd') !== false;
  252. if (!$this->isPureFtpd) {
  253. // switch off extended passive mode - may be usefull for some servers
  254. // this command, for pure-ftpd, doesn't work and takes a timeout in some pure-ftpd versions
  255. ftp_raw($this->connect, 'epsv4 off');
  256. }
  257. // enter passive mode if required
  258. $pasv = ($this->options['mode'] == 'passive');
  259. if (!ftp_pasv($this->connect, $pasv)) {
  260. if ($pasv) {
  261. $this->options['mode'] = 'active';
  262. }
  263. }
  264. // enter root folder
  265. if (!ftp_chdir($this->connect, $this->root)
  266. || $this->root != ftp_pwd($this->connect)) {
  267. $this->umount();
  268. return $this->setError('Unable to open root folder.');
  269. }
  270. // check for MLST support
  271. $features = ftp_raw($this->connect, 'FEAT');
  272. if (!is_array($features)) {
  273. $this->umount();
  274. return $this->setError('Server does not support command FEAT.');
  275. }
  276. foreach ($features as $feat) {
  277. if (strpos(trim($feat), 'MLST') === 0) {
  278. $this->MLSTsupprt = true;
  279. break;
  280. }
  281. }
  282. return true;
  283. }
  284. /**
  285. * Call ftp_rawlist with option prefix
  286. *
  287. * @param string $path
  288. *
  289. * @return array
  290. */
  291. protected function ftpRawList($path)
  292. {
  293. if ($this->isPureFtpd) {
  294. $path = str_replace(' ', '\ ', $path);
  295. }
  296. if ($this->ftpListOption) {
  297. $path = $this->ftpListOption . ' ' . $path;
  298. }
  299. $res = ftp_rawlist($this->connect, $path);
  300. if ($res === false) {
  301. $res = array();
  302. }
  303. return $res;
  304. }
  305. /*********************************************************************/
  306. /* FS API */
  307. /*********************************************************************/
  308. /**
  309. * Close opened connection
  310. *
  311. * @return void
  312. * @author Dmitry (dio) Levashov
  313. **/
  314. public function umount()
  315. {
  316. $this->connect && ftp_close($this->connect);
  317. }
  318. /**
  319. * Parse line from ftp_rawlist() output and return file stat (array)
  320. *
  321. * @param string $raw line from ftp_rawlist() output
  322. * @param $base
  323. * @param bool $nameOnly
  324. *
  325. * @return array
  326. * @author Dmitry Levashov
  327. */
  328. protected function parseRaw($raw, $base, $nameOnly = false)
  329. {
  330. static $now;
  331. static $lastyear;
  332. if (!$now) {
  333. $now = time();
  334. $lastyear = date('Y') - 1;
  335. }
  336. $info = preg_split("/\s+/", $raw, 8);
  337. if (isset($info[7])) {
  338. list($info[7], $info[8]) = explode(' ', $info[7], 2);
  339. }
  340. $stat = array();
  341. if (!isset($this->ftpOsUnix)) {
  342. $this->ftpOsUnix = !preg_match('/\d/', substr($info[0], 0, 1));
  343. }
  344. if (!$this->ftpOsUnix) {
  345. $info = $this->normalizeRawWindows($raw);
  346. }
  347. if (count($info) < 9 || $info[8] == '.' || $info[8] == '..') {
  348. return false;
  349. }
  350. $name = $info[8];
  351. if (preg_match('|(.+)\-\>(.+)|', $name, $m)) {
  352. $name = trim($m[1]);
  353. // check recursive processing
  354. if ($this->cacheDirTarget && $this->_joinPath($base, $name) !== $this->cacheDirTarget) {
  355. return array();
  356. }
  357. if (!$nameOnly) {
  358. $target = trim($m[2]);
  359. if (substr($target, 0, 1) !== $this->separator) {
  360. $target = $this->getFullPath($target, $base);
  361. }
  362. $target = $this->_normpath($target);
  363. $stat['name'] = $name;
  364. $stat['target'] = $target;
  365. return $stat;
  366. }
  367. }
  368. if ($nameOnly) {
  369. return array('name' => $name);
  370. }
  371. if (is_numeric($info[5]) && !$info[6] && !$info[7]) {
  372. // by normalizeRawWindows()
  373. $stat['ts'] = $info[5];
  374. } else {
  375. $stat['ts'] = strtotime($info[5] . ' ' . $info[6] . ' ' . $info[7]);
  376. if ($stat['ts'] && $stat['ts'] > $now && strpos($info[7], ':') !== false) {
  377. $stat['ts'] = strtotime($info[5] . ' ' . $info[6] . ' ' . $lastyear . ' ' . $info[7]);
  378. }
  379. if (empty($stat['ts'])) {
  380. $stat['ts'] = strtotime($info[6] . ' ' . $info[5] . ' ' . $info[7]);
  381. if ($stat['ts'] && $stat['ts'] > $now && strpos($info[7], ':') !== false) {
  382. $stat['ts'] = strtotime($info[6] . ' ' . $info[5] . ' ' . $lastyear . ' ' . $info[7]);
  383. }
  384. }
  385. }
  386. if ($this->options['statOwner']) {
  387. $stat['owner'] = $info[2];
  388. $stat['group'] = $info[3];
  389. $stat['perm'] = substr($info[0], 1);
  390. //
  391. // if not exists owner in LS ftp ==> isowner = true
  392. // if is defined as option : 'owner' => true isowner = true
  393. //
  394. // if exist owner in LS ftp and 'owner' => False isowner = result of owner(file) == user(logged with ftp)
  395. //
  396. $stat['isowner'] = isset($stat['owner']) ? ($this->options['owner'] ? true : ($stat['owner'] == $this->options['user'])) : true;
  397. }
  398. $owner_computed = isset($stat['isowner']) ? $stat['isowner'] : $this->options['owner'];
  399. $perm = $this->parsePermissions($info[0], $owner_computed);
  400. $stat['name'] = $name;
  401. $stat['mime'] = substr(strtolower($info[0]), 0, 1) == 'd' ? 'directory' : $this->mimetype($stat['name'], true);
  402. $stat['size'] = $stat['mime'] == 'directory' ? 0 : $info[4];
  403. $stat['read'] = $perm['read'];
  404. $stat['write'] = $perm['write'];
  405. return $stat;
  406. }
  407. /**
  408. * Normalize MS-DOS style FTP LIST Raw line
  409. *
  410. * @param string $raw line from FTP LIST (MS-DOS style)
  411. *
  412. * @return array
  413. * @author Naoki Sawada
  414. **/
  415. protected function normalizeRawWindows($raw)
  416. {
  417. $info = array_pad(array(), 9, '');
  418. $item = preg_replace('#\s+#', ' ', trim($raw), 3);
  419. list($date, $time, $size, $name) = explode(' ', $item, 4);
  420. $format = strlen($date) === 8 ? 'm-d-yH:iA' : 'Y-m-dH:i';
  421. $dateObj = DateTime::createFromFormat($format, $date . $time);
  422. $info[5] = strtotime($dateObj->format('Y-m-d H:i'));
  423. $info[8] = $name;
  424. if ($size === '<DIR>') {
  425. $info[4] = 0;
  426. $info[0] = 'drwxr-xr-x';
  427. } else {
  428. $info[4] = (int)$size;
  429. $info[0] = '-rw-r--r--';
  430. }
  431. return $info;
  432. }
  433. /**
  434. * Parse permissions string. Return array(read => true/false, write => true/false)
  435. *
  436. * @param string $perm permissions string 'rwx' + 'rwx' + 'rwx'
  437. * ^ ^ ^
  438. * | | +-> others
  439. * | +---------> group
  440. * +-----------------> owner
  441. * The isowner parameter is computed by the caller.
  442. * If the owner parameter in the options is true, the user is the actual owner of all objects even if che user used in the ftp Login
  443. * is different from the file owner id.
  444. * If the owner parameter is false to understand if the user is the file owner we compare the ftp user with the file owner id.
  445. * @param Boolean $isowner . Tell if the current user is the owner of the object.
  446. *
  447. * @return array
  448. * @author Dmitry (dio) Levashov
  449. * @author Ugo Vierucci
  450. */
  451. protected function parsePermissions($perm, $isowner = true)
  452. {
  453. $res = array();
  454. $parts = array();
  455. for ($i = 0, $l = strlen($perm); $i < $l; $i++) {
  456. $parts[] = substr($perm, $i, 1);
  457. }
  458. $read = ($isowner && $parts[1] == 'r') || $parts[4] == 'r' || $parts[7] == 'r';
  459. return array(
  460. 'read' => $parts[0] == 'd' ? $read && (($isowner && $parts[3] == 'x') || $parts[6] == 'x' || $parts[9] == 'x') : $read,
  461. 'write' => ($isowner && $parts[2] == 'w') || $parts[5] == 'w' || $parts[8] == 'w'
  462. );
  463. }
  464. /**
  465. * Cache dir contents
  466. *
  467. * @param string $path dir path
  468. *
  469. * @return void
  470. * @author Dmitry Levashov
  471. **/
  472. protected function cacheDir($path)
  473. {
  474. $this->dirsCache[$path] = array();
  475. $hasDir = false;
  476. $list = array();
  477. $encPath = $this->convEncIn($path);
  478. foreach ($this->ftpRawList($encPath) as $raw) {
  479. if (($stat = $this->parseRaw($raw, $encPath))) {
  480. $list[] = $stat;
  481. }
  482. }
  483. $list = $this->convEncOut($list);
  484. $prefix = ($path === $this->separator) ? $this->separator : $path . $this->separator;
  485. $targets = array();
  486. foreach ($list as $stat) {
  487. $p = $prefix . $stat['name'];
  488. if (isset($stat['target'])) {
  489. // stat later
  490. $targets[$stat['name']] = $stat['target'];
  491. } else {
  492. $stat = $this->updateCache($p, $stat);
  493. if (empty($stat['hidden'])) {
  494. if (!$hasDir && $stat['mime'] === 'directory') {
  495. $hasDir = true;
  496. }
  497. $this->dirsCache[$path][] = $p;
  498. }
  499. }
  500. }
  501. // stat link targets
  502. foreach ($targets as $name => $target) {
  503. $stat = array();
  504. $stat['name'] = $name;
  505. $p = $prefix . $name;
  506. $cacheDirTarget = $this->cacheDirTarget;
  507. $this->cacheDirTarget = $this->convEncIn($target, true);
  508. if ($tstat = $this->stat($target)) {
  509. $stat['size'] = $tstat['size'];
  510. $stat['alias'] = $target;
  511. $stat['thash'] = $tstat['hash'];
  512. $stat['mime'] = $tstat['mime'];
  513. $stat['read'] = $tstat['read'];
  514. $stat['write'] = $tstat['write'];
  515. if (isset($tstat['ts'])) {
  516. $stat['ts'] = $tstat['ts'];
  517. }
  518. if (isset($tstat['owner'])) {
  519. $stat['owner'] = $tstat['owner'];
  520. }
  521. if (isset($tstat['group'])) {
  522. $stat['group'] = $tstat['group'];
  523. }
  524. if (isset($tstat['perm'])) {
  525. $stat['perm'] = $tstat['perm'];
  526. }
  527. if (isset($tstat['isowner'])) {
  528. $stat['isowner'] = $tstat['isowner'];
  529. }
  530. } else {
  531. $stat['mime'] = 'symlink-broken';
  532. $stat['read'] = false;
  533. $stat['write'] = false;
  534. $stat['size'] = 0;
  535. }
  536. $this->cacheDirTarget = $cacheDirTarget;
  537. $stat = $this->updateCache($p, $stat);
  538. if (empty($stat['hidden'])) {
  539. if (!$hasDir && $stat['mime'] === 'directory') {
  540. $hasDir = true;
  541. }
  542. $this->dirsCache[$path][] = $p;
  543. }
  544. }
  545. if (isset($this->sessionCache['subdirs'])) {
  546. $this->sessionCache['subdirs'][$path] = $hasDir;
  547. }
  548. }
  549. /**
  550. * Return ftp transfer mode for file
  551. *
  552. * @param string $path file path
  553. *
  554. * @return string
  555. * @author Dmitry (dio) Levashov
  556. **/
  557. protected function ftpMode($path)
  558. {
  559. return strpos($this->mimetype($path), 'text/') === 0 ? FTP_ASCII : FTP_BINARY;
  560. }
  561. /*********************** paths/urls *************************/
  562. /**
  563. * Return parent directory path
  564. *
  565. * @param string $path file path
  566. *
  567. * @return string
  568. * @author Naoki Sawada
  569. **/
  570. protected function _dirname($path)
  571. {
  572. $parts = explode($this->separator, trim($path, $this->separator));
  573. array_pop($parts);
  574. return $this->separator . join($this->separator, $parts);
  575. }
  576. /**
  577. * Return file name
  578. *
  579. * @param string $path file path
  580. *
  581. * @return string
  582. * @author Naoki Sawada
  583. **/
  584. protected function _basename($path)
  585. {
  586. $parts = explode($this->separator, trim($path, $this->separator));
  587. return array_pop($parts);
  588. }
  589. /**
  590. * Join dir name and file name and retur full path
  591. *
  592. * @param string $dir
  593. * @param string $name
  594. *
  595. * @return string
  596. * @author Dmitry (dio) Levashov
  597. **/
  598. protected function _joinPath($dir, $name)
  599. {
  600. return rtrim($dir, $this->separator) . $this->separator . $name;
  601. }
  602. /**
  603. * Return normalized path, this works the same as os.path.normpath() in Python
  604. *
  605. * @param string $path path
  606. *
  607. * @return string
  608. * @author Troex Nevelin
  609. **/
  610. protected function _normpath($path)
  611. {
  612. if (empty($path)) {
  613. $path = '.';
  614. }
  615. // path must be start with /
  616. $path = preg_replace('|^\.\/?|', $this->separator, $path);
  617. $path = preg_replace('/^([^\/])/', "/$1", $path);
  618. if ($path[0] === $this->separator) {
  619. $initial_slashes = true;
  620. } else {
  621. $initial_slashes = false;
  622. }
  623. if (($initial_slashes)
  624. && (strpos($path, '//') === 0)
  625. && (strpos($path, '///') === false)) {
  626. $initial_slashes = 2;
  627. }
  628. $initial_slashes = (int)$initial_slashes;
  629. $comps = explode($this->separator, $path);
  630. $new_comps = array();
  631. foreach ($comps as $comp) {
  632. if (in_array($comp, array('', '.'))) {
  633. continue;
  634. }
  635. if (($comp != '..')
  636. || (!$initial_slashes && !$new_comps)
  637. || ($new_comps && (end($new_comps) == '..'))) {
  638. array_push($new_comps, $comp);
  639. } elseif ($new_comps) {
  640. array_pop($new_comps);
  641. }
  642. }
  643. $comps = $new_comps;
  644. $path = implode($this->separator, $comps);
  645. if ($initial_slashes) {
  646. $path = str_repeat($this->separator, $initial_slashes) . $path;
  647. }
  648. return $path ? $path : '.';
  649. }
  650. /**
  651. * Return file path related to root dir
  652. *
  653. * @param string $path file path
  654. *
  655. * @return string
  656. * @author Dmitry (dio) Levashov
  657. **/
  658. protected function _relpath($path)
  659. {
  660. if ($path === $this->root) {
  661. return '';
  662. } else {
  663. if (strpos($path, $this->root) === 0) {
  664. return ltrim(substr($path, strlen($this->root)), $this->separator);
  665. } else {
  666. // for link
  667. return $path;
  668. }
  669. }
  670. }
  671. /**
  672. * Convert path related to root dir into real path
  673. *
  674. * @param string $path file path
  675. *
  676. * @return string
  677. * @author Dmitry (dio) Levashov
  678. **/
  679. protected function _abspath($path)
  680. {
  681. if ($path === $this->separator) {
  682. return $this->root;
  683. } else {
  684. if ($path[0] === $this->separator) {
  685. // for link
  686. return $path;
  687. } else {
  688. return $this->_joinPath($this->root, $path);
  689. }
  690. }
  691. }
  692. /**
  693. * Return fake path started from root dir
  694. *
  695. * @param string $path file path
  696. *
  697. * @return string
  698. * @author Dmitry (dio) Levashov
  699. **/
  700. protected function _path($path)
  701. {
  702. return $this->rootName . ($path == $this->root ? '' : $this->separator . $this->_relpath($path));
  703. }
  704. /**
  705. * Return true if $path is children of $parent
  706. *
  707. * @param string $path path to check
  708. * @param string $parent parent path
  709. *
  710. * @return bool
  711. * @author Dmitry (dio) Levashov
  712. **/
  713. protected function _inpath($path, $parent)
  714. {
  715. return $path == $parent || strpos($path, rtrim($parent, $this->separator) . $this->separator) === 0;
  716. }
  717. /***************** file stat ********************/
  718. /**
  719. * Return stat for given path.
  720. * Stat contains following fields:
  721. * - (int) size file size in b. required
  722. * - (int) ts file modification time in unix time. required
  723. * - (string) mime mimetype. required for folders, others - optionally
  724. * - (bool) read read permissions. required
  725. * - (bool) write write permissions. required
  726. * - (bool) locked is object locked. optionally
  727. * - (bool) hidden is object hidden. optionally
  728. * - (string) alias for symlinks - link target path relative to root path. optionally
  729. * - (string) target for symlinks - link target path. optionally
  730. * If file does not exists - returns empty array or false.
  731. *
  732. * @param string $path file path
  733. *
  734. * @return array|false
  735. * @author Dmitry (dio) Levashov
  736. **/
  737. protected function _stat($path)
  738. {
  739. $outPath = $this->convEncOut($path);
  740. if (isset($this->cache[$outPath])) {
  741. return $this->convEncIn($this->cache[$outPath]);
  742. } else {
  743. $this->convEncIn();
  744. }
  745. if (!$this->MLSTsupprt) {
  746. if ($path === $this->root) {
  747. $res = array(
  748. 'name' => $this->root,
  749. 'mime' => 'directory',
  750. 'dirs' => -1
  751. );
  752. if ($this->needOnline && (($this->ARGS['cmd'] === 'open' && $this->ARGS['target'] === $this->encode($this->root)) || $this->isMyReload())) {
  753. $check = array(
  754. 'ts' => true,
  755. 'dirs' => true,
  756. );
  757. $ts = 0;
  758. foreach ($this->ftpRawList($path) as $str) {
  759. $info = preg_split('/\s+/', $str, 9);
  760. if ($info[8] === '.') {
  761. $info[8] = 'root';
  762. if ($stat = $this->parseRaw(join(' ', $info), $path)) {
  763. unset($stat['name']);
  764. $res = array_merge($res, $stat);
  765. if ($res['ts']) {
  766. $ts = 0;
  767. unset($check['ts']);
  768. }
  769. }
  770. }
  771. if ($check && ($stat = $this->parseRaw($str, $path))) {
  772. if (isset($stat['ts']) && !empty($stat['ts'])) {
  773. $ts = max($ts, $stat['ts']);
  774. }
  775. if (isset($stat['dirs']) && $stat['mime'] === 'directory') {
  776. $res['dirs'] = 1;
  777. unset($stat['dirs']);
  778. }
  779. if (!$check) {
  780. break;
  781. }
  782. }
  783. }
  784. if ($ts) {
  785. $res['ts'] = $ts;
  786. }
  787. $this->cache[$outPath] = $res;
  788. }
  789. return $res;
  790. }
  791. $pPath = $this->_dirname($path);
  792. if ($this->_inPath($pPath, $this->root)) {
  793. $outPPpath = $this->convEncOut($pPath);
  794. if (!isset($this->dirsCache[$outPPpath])) {
  795. $parentSubdirs = null;
  796. if (isset($this->sessionCache['subdirs']) && isset($this->sessionCache['subdirs'][$outPPpath])) {
  797. $parentSubdirs = $this->sessionCache['subdirs'][$outPPpath];
  798. }
  799. $this->cacheDir($outPPpath);
  800. if ($parentSubdirs) {
  801. $this->sessionCache['subdirs'][$outPPpath] = $parentSubdirs;
  802. }
  803. }
  804. }
  805. $stat = $this->convEncIn(isset($this->cache[$outPath]) ? $this->cache[$outPath] : array());
  806. if (!$this->mounted) {
  807. // dispose incomplete cache made by calling `stat` by 'startPath' option
  808. $this->cache = array();
  809. }
  810. return $stat;
  811. }
  812. $raw = ftp_raw($this->connect, 'MLST ' . $path);
  813. if (is_array($raw) && count($raw) > 1 && substr(trim($raw[0]), 0, 1) == 2) {
  814. $parts = explode(';', trim($raw[1]));
  815. array_pop($parts);
  816. $parts = array_map('strtolower', $parts);
  817. $stat = array();
  818. $mode = '';
  819. foreach ($parts as $part) {
  820. list($key, $val) = explode('=', $part, 2);
  821. switch ($key) {
  822. case 'type':
  823. if (strpos($val, 'dir') !== false) {
  824. $stat['mime'] = 'directory';
  825. } else if (strpos($val, 'link') !== false) {
  826. $stat['mime'] = 'symlink';
  827. break(2);
  828. } else {
  829. $stat['mime'] = $this->mimetype($path);
  830. }
  831. break;
  832. case 'size':
  833. $stat['size'] = $val;
  834. break;
  835. case 'modify':
  836. $ts = mktime(intval(substr($val, 8, 2)), intval(substr($val, 10, 2)), intval(substr($val, 12, 2)), intval(substr($val, 4, 2)), intval(substr($val, 6, 2)), substr($val, 0, 4));
  837. $stat['ts'] = $ts;
  838. break;
  839. case 'unix.mode':
  840. $mode = strval($val);
  841. break;
  842. case 'unix.uid':
  843. $stat['owner'] = $val;
  844. break;
  845. case 'unix.gid':
  846. $stat['group'] = $val;
  847. break;
  848. case 'perm':
  849. $val = strtolower($val);
  850. $stat['read'] = (int)preg_match('/e|l|r/', $val);
  851. $stat['write'] = (int)preg_match('/w|m|c/', $val);
  852. if (!preg_match('/f|d/', $val)) {
  853. $stat['locked'] = 1;
  854. }
  855. break;
  856. }
  857. }
  858. if (empty($stat['mime'])) {
  859. return array();
  860. }
  861. // do not use MLST to get stat of symlink
  862. if ($stat['mime'] === 'symlink') {
  863. $this->MLSTsupprt = false;
  864. $res = $this->_stat($path);
  865. $this->MLSTsupprt = true;
  866. return $res;
  867. }
  868. if ($stat['mime'] === 'directory') {
  869. $stat['size'] = 0;
  870. }
  871. if ($mode) {
  872. $stat['perm'] = '';
  873. if ($mode[0] === '0') {
  874. $mode = substr($mode, 1);
  875. }
  876. $perm = array();
  877. for ($i = 0; $i <= 2; $i++) {
  878. $perm[$i] = array(false, false, false);
  879. $n = isset($mode[$i]) ? $mode[$i] : 0;
  880. if ($n - 4 >= 0) {
  881. $perm[$i][0] = true;
  882. $n = $n - 4;
  883. $stat['perm'] .= 'r';
  884. } else {
  885. $stat['perm'] .= '-';
  886. }
  887. if ($n - 2 >= 0) {
  888. $perm[$i][1] = true;
  889. $n = $n - 2;
  890. $stat['perm'] .= 'w';
  891. } else {
  892. $stat['perm'] .= '-';
  893. }
  894. if ($n - 1 == 0) {
  895. $perm[$i][2] = true;
  896. $stat['perm'] .= 'x';
  897. } else {
  898. $stat['perm'] .= '-';
  899. }
  900. }
  901. $stat['perm'] = trim($stat['perm']);
  902. //
  903. // if not exists owner in LS ftp ==> isowner = true
  904. // if is defined as option : 'owner' => true isowner = true
  905. //
  906. // if exist owner in LS ftp and 'owner' => False isowner = result of owner(file) == user(logged with ftp)
  907. $owner_computed = isset($stat['owner']) ? ($this->options['owner'] ? true : ($stat['owner'] == $this->options['user'])) : true;
  908. $read = ($owner_computed && $perm[0][0]) || $perm[1][0] || $perm[2][0];
  909. $stat['read'] = $stat['mime'] == 'directory' ? $read && (($owner_computed && $perm[0][2]) || $perm[1][2] || $perm[2][2]) : $read;
  910. $stat['write'] = ($owner_computed && $perm[0][1]) || $perm[1][1] || $perm[2][1];
  911. if ($this->options['statOwner']) {
  912. $stat['isowner'] = $owner_computed;
  913. } else {
  914. unset($stat['owner'], $stat['group'], $stat['perm']);
  915. }
  916. }
  917. return $stat;
  918. }
  919. return array();
  920. }
  921. /**
  922. * Return true if path is dir and has at least one childs directory
  923. *
  924. * @param string $path dir path
  925. *
  926. * @return bool
  927. * @author Dmitry (dio) Levashov
  928. **/
  929. protected function _subdirs($path)
  930. {
  931. foreach ($this->ftpRawList($path) as $str) {
  932. $info = preg_split('/\s+/', $str, 9);
  933. if (!isset($this->ftpOsUnix)) {
  934. $this->ftpOsUnix = !preg_match('/\d/', substr($info[0], 0, 1));
  935. }
  936. if (!$this->ftpOsUnix) {
  937. $info = $this->normalizeRawWindows($str);
  938. }
  939. $name = isset($info[8]) ? trim($info[8]) : '';
  940. if ($name && $name !== '.' && $name !== '..' && substr(strtolower($info[0]), 0, 1) === 'd') {
  941. return true;
  942. }
  943. }
  944. return false;
  945. }
  946. /**
  947. * Return object width and height
  948. * Ususaly used for images, but can be realize for video etc...
  949. *
  950. * @param string $path file path
  951. * @param string $mime file mime type
  952. *
  953. * @return string|false
  954. * @throws ImagickException
  955. * @throws elFinderAbortException
  956. * @author Dmitry (dio) Levashov
  957. */
  958. protected function _dimensions($path, $mime)
  959. {
  960. $ret = false;
  961. if ($imgsize = $this->getImageSize($path, $mime)) {
  962. $ret = array('dim' => $imgsize['dimensions']);
  963. if (!empty($imgsize['url'])) {
  964. $ret['url'] = $imgsize['url'];
  965. }
  966. }
  967. return $ret;
  968. }
  969. /******************** file/dir content *********************/
  970. /**
  971. * Return files list in directory.
  972. *
  973. * @param string $path dir path
  974. *
  975. * @return array
  976. * @author Dmitry (dio) Levashov
  977. * @author Cem (DiscoFever)
  978. **/
  979. protected function _scandir($path)
  980. {
  981. $files = array();
  982. foreach ($this->ftpRawList($path) as $str) {
  983. if (($stat = $this->parseRaw($str, $path, true))) {
  984. $files[] = $this->_joinPath($path, $stat['name']);
  985. }
  986. }
  987. return $files;
  988. }
  989. /**
  990. * Open file and return file pointer
  991. *
  992. * @param string $path file path
  993. * @param string $mode
  994. *
  995. * @return false|resource
  996. * @throws elFinderAbortException
  997. * @internal param bool $write open file for writing
  998. * @author Dmitry (dio) Levashov
  999. */
  1000. protected function _fopen($path, $mode = 'rb')
  1001. {
  1002. // try ftp stream wrapper
  1003. if ($this->options['mode'] === 'passive' && ini_get('allow_url_fopen')) {
  1004. $url = ($this->isFTPS ? 'ftps' : 'ftp') . '://' . $this->options['user'] . ':' . $this->options['pass'] . '@' . $this->options['host'] . ':' . $this->options['port'] . $path;
  1005. if (strtolower($mode[0]) === 'w') {
  1006. $context = stream_context_create(array('ftp' => array('overwrite' => true)));
  1007. $fp = fopen($url, $mode, false, $context);
  1008. } else {
  1009. $fp = fopen($url, $mode);
  1010. }
  1011. if ($fp) {
  1012. return $fp;
  1013. }
  1014. }
  1015. if ($this->tmp) {
  1016. $local = $this->getTempFile($path);
  1017. $fp = fopen($local, 'wb');
  1018. $ret = ftp_nb_fget($this->connect, $fp, $path, FTP_BINARY);
  1019. while ($ret === FTP_MOREDATA) {
  1020. elFinder::extendTimeLimit();
  1021. $ret = ftp_nb_continue($this->connect);
  1022. }
  1023. if ($ret === FTP_FINISHED) {
  1024. fclose($fp);
  1025. $fp = fopen($local, $mode);
  1026. return $fp;
  1027. }
  1028. fclose($fp);
  1029. is_file($local) && unlink($local);
  1030. }
  1031. return false;
  1032. }
  1033. /**
  1034. * Close opened file
  1035. *
  1036. * @param resource $fp file pointer
  1037. * @param string $path
  1038. *
  1039. * @return void
  1040. * @author Dmitry (dio) Levashov
  1041. */
  1042. protected function _fclose($fp, $path = '')
  1043. {
  1044. is_resource($fp) && fclose($fp);
  1045. if ($path) {
  1046. unlink($this->getTempFile($path));
  1047. }
  1048. }
  1049. /******************** file/dir manipulations *************************/
  1050. /**
  1051. * Create dir and return created dir path or false on failed
  1052. *
  1053. * @param string $path parent dir path
  1054. * @param string $name new directory name
  1055. *
  1056. * @return string|bool
  1057. * @author Dmitry (dio) Levashov
  1058. **/
  1059. protected function _mkdir($path, $name)
  1060. {
  1061. $path = $this->_joinPath($path, $name);
  1062. if (ftp_mkdir($this->connect, $path) === false) {
  1063. return false;
  1064. }
  1065. $this->options['dirMode'] && ftp_chmod($this->connect, $this->options['dirMode'], $path);
  1066. return $path;
  1067. }
  1068. /**
  1069. * Create file and return it's path or false on failed
  1070. *
  1071. * @param string $path parent dir path
  1072. * @param string $name new file name
  1073. *
  1074. * @return string|bool
  1075. * @author Dmitry (dio) Levashov
  1076. **/
  1077. protected function _mkfile($path, $name)
  1078. {
  1079. if ($this->tmp) {
  1080. $path = $this->_joinPath($path, $name);
  1081. $local = $this->getTempFile();
  1082. $res = touch($local) && ftp_put($this->connect, $path, $local, FTP_ASCII);
  1083. unlink($local);
  1084. return $res ? $path : false;
  1085. }
  1086. return false;
  1087. }
  1088. /**
  1089. * Create symlink. FTP driver does not support symlinks.
  1090. *
  1091. * @param string $target link target
  1092. * @param string $path symlink path
  1093. * @param string $name
  1094. *
  1095. * @return bool
  1096. * @author Dmitry (dio) Levashov
  1097. */
  1098. protected function _symlink($target, $path, $name)
  1099. {
  1100. return false;
  1101. }
  1102. /**
  1103. * Copy file into another file
  1104. *
  1105. * @param string $source source file path
  1106. * @param string $targetDir target directory path
  1107. * @param string $name new file name
  1108. *
  1109. * @return bool
  1110. * @author Dmitry (dio) Levashov
  1111. **/
  1112. protected function _copy($source, $targetDir, $name)
  1113. {
  1114. $res = false;
  1115. if ($this->tmp) {
  1116. $local = $this->getTempFile();
  1117. $target = $this->_joinPath($targetDir, $name);
  1118. if (ftp_get($this->connect, $local, $source, FTP_BINARY)
  1119. && ftp_put($this->connect, $target, $local, $this->ftpMode($target))) {
  1120. $res = $target;
  1121. }
  1122. unlink($local);
  1123. }
  1124. return $res;
  1125. }
  1126. /**
  1127. * Move file into another parent dir.
  1128. * Return new file path or false.
  1129. *
  1130. * @param string $source source file path
  1131. * @param $targetDir
  1132. * @param string $name file name
  1133. *
  1134. * @return bool|string
  1135. * @internal param string $target target dir path
  1136. * @author Dmitry (dio) Levashov
  1137. */
  1138. protected function _move($source, $targetDir, $name)
  1139. {
  1140. $target = $this->_joinPath($targetDir, $name);
  1141. return ftp_rename($this->connect, $source, $target) ? $target : false;
  1142. }
  1143. /**
  1144. * Remove file
  1145. *
  1146. * @param string $path file path
  1147. *
  1148. * @return bool
  1149. * @author Dmitry (dio) Levashov
  1150. **/
  1151. protected function _unlink($path)
  1152. {
  1153. return ftp_delete($this->connect, $path);
  1154. }
  1155. /**
  1156. * Remove dir
  1157. *
  1158. * @param string $path dir path
  1159. *
  1160. * @return bool
  1161. * @author Dmitry (dio) Levashov
  1162. **/
  1163. protected function _rmdir($path)
  1164. {
  1165. return ftp_rmdir($this->connect, $path);
  1166. }
  1167. /**
  1168. * Create new file and write into it from file pointer.
  1169. * Return new file path or false on error.
  1170. *
  1171. * @param resource $fp file pointer
  1172. * @param string $dir target dir path
  1173. * @param string $name file name
  1174. * @param array $stat file stat (required by some virtual fs)
  1175. *
  1176. * @return bool|string
  1177. * @author Dmitry (dio) Levashov
  1178. **/
  1179. protected function _save($fp, $dir, $name, $stat)
  1180. {
  1181. $path = $this->_joinPath($dir, $name);
  1182. return ftp_fput($this->connect, $path, $fp, $this->ftpMode($path))
  1183. ? $path
  1184. : false;
  1185. }
  1186. /**
  1187. * Get file contents
  1188. *
  1189. * @param string $path file path
  1190. *
  1191. * @return string|false
  1192. * @throws elFinderAbortException
  1193. * @author Dmitry (dio) Levashov
  1194. */
  1195. protected function _getContents($path)
  1196. {
  1197. $contents = '';
  1198. if (($fp = $this->_fopen($path))) {
  1199. while (!feof($fp)) {
  1200. $contents .= fread($fp, 8192);
  1201. }
  1202. $this->_fclose($fp, $path);
  1203. return $contents;
  1204. }
  1205. return false;
  1206. }
  1207. /**
  1208. * Write a string to a file
  1209. *
  1210. * @param string $path file path
  1211. * @param string $content new file content
  1212. *
  1213. * @return bool
  1214. * @author Dmitry (dio) Levashov
  1215. **/
  1216. protected function _filePutContents($path, $content)
  1217. {
  1218. $res = false;
  1219. if ($this->tmp) {
  1220. $local = $this->getTempFile();
  1221. if (file_put_contents($local, $content, LOCK_EX) !== false
  1222. && ($fp = fopen($local, 'rb'))) {
  1223. $file = $this->stat($this->convEncOut($path, false));
  1224. if (!empty($file['thash'])) {
  1225. $path = $this->decode($file['thash']);
  1226. }
  1227. clearstatcache();
  1228. $res = ftp_fput($this->connect, $path, $fp, $this->ftpMode($path));
  1229. fclose($fp);
  1230. }
  1231. file_exists($local) && unlink($local);
  1232. }
  1233. return $res;
  1234. }
  1235. /**
  1236. * Detect available archivers
  1237. *
  1238. * @return void
  1239. * @throws elFinderAbortException
  1240. */
  1241. protected function _checkArchivers()
  1242. {
  1243. $this->archivers = $this->getArchivers();
  1244. return;
  1245. }
  1246. /**
  1247. * chmod availability
  1248. *
  1249. * @param string $path
  1250. * @param string $mode
  1251. *
  1252. * @return bool
  1253. */
  1254. protected function _chmod($path, $mode)
  1255. {
  1256. $modeOct = is_string($mode) ? octdec($mode) : octdec(sprintf("%04o", $mode));
  1257. return ftp_chmod($this->connect, $modeOct, $path);
  1258. }
  1259. /**
  1260. * Extract files from archive
  1261. *
  1262. * @param string $path archive path
  1263. * @param array $arc archiver command and arguments (same as in $this->archivers)
  1264. *
  1265. * @return true
  1266. * @throws elFinderAbortException
  1267. * @author Dmitry (dio) Levashov,
  1268. * @author Alexey Sukhotin
  1269. */
  1270. protected function _extract($path, $arc)
  1271. {
  1272. $dir = $this->tempDir();
  1273. if (!$dir) {
  1274. return false;
  1275. }
  1276. $basename = $this->_basename($path);
  1277. $localPath = $dir . DIRECTORY_SEPARATOR . $basename;
  1278. if (!ftp_get($this->connect, $localPath, $path, FTP_BINARY)) {
  1279. //cleanup
  1280. $this->rmdirRecursive($dir);
  1281. return false;
  1282. }
  1283. $this->unpackArchive($localPath, $arc);
  1284. $this->archiveSize = 0;
  1285. // find symlinks and check extracted items
  1286. $checkRes = $this->checkExtractItems($dir);
  1287. if ($checkRes['symlinks']) {
  1288. $this->rmdirRecursive($dir);
  1289. return $this->setError(array_merge($this->error, array(elFinder::ERROR_ARC_SYMLINKS)));
  1290. }
  1291. $this->archiveSize = $checkRes['totalSize'];
  1292. if ($checkRes['rmNames']) {
  1293. foreach ($checkRes['rmNames'] as $name) {
  1294. $this->addError(elFinder::ERROR_SAVE, $name);
  1295. }
  1296. }
  1297. $filesToProcess = self::listFilesInDirectory($dir, true);
  1298. // no files - extract error ?
  1299. if (empty($filesToProcess)) {
  1300. $this->rmdirRecursive($dir);
  1301. return false;
  1302. }
  1303. // check max files size
  1304. if ($this->options['maxArcFilesSize'] > 0 && $this->options['maxArcFilesSize'] < $this->archiveSize) {
  1305. $this->rmdirRecursive($dir);
  1306. return $this->setError(elFinder::ERROR_ARC_MAXSIZE);
  1307. }
  1308. $extractTo = $this->extractToNewdir; // 'auto', ture or false
  1309. // archive contains one item - extract in archive dir
  1310. $name = '';
  1311. $src = $dir . DIRECTORY_SEPARATOR . $filesToProcess[0];
  1312. if (($extractTo === 'auto' || !$extractTo) && count($filesToProcess) === 1 && is_file($src)) {
  1313. $name = $filesToProcess[0];
  1314. } else if ($extractTo === 'auto' || $extractTo) {
  1315. // for several files - create new directory
  1316. // create unique name for directory
  1317. $src = $dir;
  1318. $splits = elFinder::splitFileExtention(basename($path));
  1319. $name = $splits[0];
  1320. $test = $this->_joinPath(dirname($path), $name);
  1321. if ($this->stat($test)) {
  1322. $name = $this->uniqueName(dirname($path), $name, '-', false);
  1323. }
  1324. }
  1325. if ($name !== '' && is_file($src)) {
  1326. $result = $this->_joinPath(dirname($path), $name);
  1327. if (!ftp_put($this->connect, $result, $src, FTP_BINARY)) {
  1328. $this->rmdirRecursive($dir);
  1329. return false;
  1330. }
  1331. } else {
  1332. $dstDir = $this->_dirname($path);
  1333. $result = array();
  1334. if (is_dir($src) && $name) {
  1335. $target = $this->_joinPath($dstDir, $name);
  1336. $_stat = $this->_stat($target);
  1337. if ($_stat) {
  1338. if (!$this->options['copyJoin']) {
  1339. if ($_stat['mime'] === 'directory') {
  1340. $this->delTree($target);
  1341. } else {
  1342. $this->_unlink($target);
  1343. }
  1344. $_stat = false;
  1345. } else {
  1346. $dstDir = $target;
  1347. }
  1348. }
  1349. if (!$_stat && (!$dstDir = $this->_mkdir($dstDir, $name))) {
  1350. $this->rmdirRecursive($dir);
  1351. return false;
  1352. }
  1353. $result[] = $dstDir;
  1354. }
  1355. foreach ($filesToProcess as $name) {
  1356. $name = rtrim($name, DIRECTORY_SEPARATOR);
  1357. $src = $dir . DIRECTORY_SEPARATOR . $name;
  1358. if (is_dir($src)) {
  1359. $p = dirname($name);
  1360. if ($p === '.') {
  1361. $p = '';
  1362. }
  1363. $name = basename($name);
  1364. $target = $this->_joinPath($this->_joinPath($dstDir, $p), $name);
  1365. $_stat = $this->_stat($target);
  1366. if ($_stat) {
  1367. if (!$this->options['copyJoin']) {
  1368. if ($_stat['mime'] === 'directory') {
  1369. $this->delTree($target);
  1370. } else {
  1371. $this->_unlink($target);
  1372. }
  1373. $_stat = false;
  1374. }
  1375. }
  1376. if (!$_stat && (!$target = $this->_mkdir($this->_joinPath($dstDir, $p), $name))) {
  1377. $this->rmdirRecursive($dir);
  1378. return false;
  1379. }
  1380. } else {
  1381. $target = $this->_joinPath($dstDir, $name);
  1382. if (!ftp_put($this->connect, $target, $src, FTP_BINARY)) {
  1383. $this->rmdirRecursive($dir);
  1384. return false;
  1385. }
  1386. }
  1387. $result[] = $target;
  1388. }
  1389. if (!$result) {
  1390. $this->rmdirRecursive($dir);
  1391. return false;
  1392. }
  1393. }
  1394. is_dir($dir) && $this->rmdirRecursive($dir);
  1395. $this->clearcache();
  1396. return $result ? $result : false;
  1397. }
  1398. /**
  1399. * Create archive and return its path
  1400. *
  1401. * @param string $dir target dir
  1402. * @param array $files files names list
  1403. * @param string $name archive name
  1404. * @param array $arc archiver options
  1405. *
  1406. * @return string|bool
  1407. * @throws elFinderAbortException
  1408. * @author Dmitry (dio) Levashov,
  1409. * @author Alexey Sukhotin
  1410. */
  1411. protected function _archive($dir, $files, $name, $arc)
  1412. {
  1413. // get current directory
  1414. $cwd = getcwd();
  1415. $tmpDir = $this->tempDir();
  1416. if (!$tmpDir) {
  1417. return false;
  1418. }
  1419. //download data
  1420. if (!$this->ftp_download_files($dir, $files, $tmpDir)) {
  1421. //cleanup
  1422. $this->rmdirRecursive($tmpDir);
  1423. return false;
  1424. }
  1425. $remoteArchiveFile = false;
  1426. if ($path = $this->makeArchive($tmpDir, $files, $name, $arc)) {
  1427. $remoteArchiveFile = $this->_joinPath($dir, $name);
  1428. if (!ftp_put($this->connect, $remoteArchiveFile, $path, FTP_BINARY)) {
  1429. $remoteArchiveFile = false;
  1430. }
  1431. }
  1432. //cleanup
  1433. if (!$this->rmdirRecursive($tmpDir)) {
  1434. return false;
  1435. }
  1436. return $remoteArchiveFile;
  1437. }
  1438. /**
  1439. * Create writable temporary directory and return path to it.
  1440. *
  1441. * @return string path to the new temporary directory or false in case of error.
  1442. */
  1443. private function tempDir()
  1444. {
  1445. $tempPath = tempnam($this->tmp, 'elFinder');
  1446. if (!$tempPath) {
  1447. $this->setError(elFinder::ERROR_CREATING_TEMP_DIR, $this->tmp);
  1448. return false;
  1449. }
  1450. $success = unlink($tempPath);
  1451. if (!$success) {
  1452. $this->setError(elFinder::ERROR_CREATING_TEMP_DIR, $this->tmp);
  1453. return false;
  1454. }
  1455. $success = mkdir($tempPath, 0700, true);
  1456. if (!$success) {
  1457. $this->setError(elFinder::ERROR_CREATING_TEMP_DIR, $this->tmp);
  1458. return false;
  1459. }
  1460. return $tempPath;
  1461. }
  1462. /**
  1463. * Gets an array of absolute remote FTP paths of files and
  1464. * folders in $remote_directory omitting symbolic links.
  1465. *
  1466. * @param $remote_directory string remote FTP path to scan for file and folders recursively
  1467. * @param $targets array Array of target item. `null` is to get all of items
  1468. *
  1469. * @return array of elements each of which is an array of two elements:
  1470. * <ul>
  1471. * <li>$item['path'] - absolute remote FTP path</li>
  1472. * <li>$item['type'] - either 'f' for file or 'd' for directory</li>
  1473. * </ul>
  1474. */
  1475. protected function ftp_scan_dir($remote_directory, $targets = null)
  1476. {
  1477. $buff = $this->ftpRawList($remote_directory);
  1478. $items = array();
  1479. if ($targets && is_array($targets)) {
  1480. $targets = array_flip($targets);
  1481. } else {
  1482. $targets = false;
  1483. }
  1484. foreach ($buff as $str) {
  1485. $info = preg_split("/\s+/", $str, 9);
  1486. if (!isset($this->ftpOsUnix)) {
  1487. $this->ftpOsUnix = !preg_match('/\d/', substr($info[0], 0, 1));
  1488. }
  1489. if (!$this->ftpOsUnix) {
  1490. $info = $this->normalizeRawWindows($str);
  1491. }
  1492. $type = substr($info[0], 0, 1);
  1493. $name = trim($info[8]);
  1494. if ($name !== '.' && $name !== '..' && (!$targets || isset($targets[$name]))) {
  1495. switch ($type) {
  1496. case 'l' : //omit symbolic links
  1497. case 'd' :
  1498. $remote_file_path = $this->_joinPath($remote_directory, $name);
  1499. $item = array();
  1500. $item['path'] = $remote_file_path;
  1501. $item['type'] = 'd'; // normal file
  1502. $items[] = $item;
  1503. $items = array_merge($items, $this->ftp_scan_dir($remote_file_path));
  1504. break;
  1505. default:
  1506. $remote_file_path = $this->_joinPath($remote_directory, $name);
  1507. $item = array();
  1508. $item['path'] = $remote_file_path;
  1509. $item['type'] = 'f'; // normal file
  1510. $items[] = $item;
  1511. }
  1512. }
  1513. }
  1514. return $items;
  1515. }
  1516. /**
  1517. * Downloads specified files from remote directory
  1518. * if there is a directory among files it is downloaded recursively (omitting symbolic links).
  1519. *
  1520. * @param $remote_directory string remote FTP path to a source directory to download from.
  1521. * @param array $files list of files to download from remote directory.
  1522. * @param $dest_local_directory string destination folder to store downloaded files.
  1523. *
  1524. * @return bool true on success and false on failure.
  1525. */
  1526. private function ftp_download_files($remote_directory, array $files, $dest_local_directory)
  1527. {
  1528. $contents = $this->ftp_scan_dir($remote_directory, $files);
  1529. if (!isset($contents)) {
  1530. $this->setError(elFinder::ERROR_FTP_DOWNLOAD_FILE, $remote_directory);
  1531. return false;
  1532. }
  1533. $remoteDirLen = strlen($remote_directory);
  1534. foreach ($contents as $item) {
  1535. $relative_path = substr($item['path'], $remoteDirLen);
  1536. $local_path = $dest_local_directory . DIRECTORY_SEPARATOR . $relative_path;
  1537. switch ($item['type']) {
  1538. case 'd':
  1539. $success = mkdir($local_path);
  1540. break;
  1541. case 'f':
  1542. $success = ftp_get($this->connect, $local_path, $item['path'], FTP_BINARY);
  1543. break;
  1544. default:
  1545. $success = true;
  1546. }
  1547. if (!$success) {
  1548. $this->setError(elFinder::ERROR_FTP_DOWNLOAD_FILE, $remote_directory);
  1549. return false;
  1550. }
  1551. }
  1552. return true;
  1553. }
  1554. /**
  1555. * Delete local directory recursively.
  1556. *
  1557. * @param $dirPath string to directory to be erased.
  1558. *
  1559. * @return bool true on success and false on failure.
  1560. * @throws Exception
  1561. */
  1562. private function deleteDir($dirPath)
  1563. {
  1564. if (!is_dir($dirPath)) {
  1565. $success = unlink($dirPath);
  1566. } else {
  1567. $success = true;
  1568. foreach (array_reverse(elFinderVolumeFTP::listFilesInDirectory($dirPath, false)) as $path) {
  1569. $path = $dirPath . DIRECTORY_SEPARATOR . $path;
  1570. if (is_link($path)) {
  1571. unlink($path);
  1572. } else if (is_dir($path)) {
  1573. $success = rmdir($path);
  1574. } else {
  1575. $success = unlink($path);
  1576. }
  1577. if (!$success) {
  1578. break;
  1579. }
  1580. }
  1581. if ($success) {
  1582. $success = rmdir($dirPath);
  1583. }
  1584. }
  1585. if (!$success) {
  1586. $this->setError(elFinder::ERROR_RM, $dirPath);
  1587. return false;
  1588. }
  1589. return $success;
  1590. }
  1591. /**
  1592. * Returns array of strings containing all files and folders in the specified local directory.
  1593. *
  1594. * @param $dir
  1595. * @param $omitSymlinks
  1596. * @param string $prefix
  1597. *
  1598. * @return array array of files and folders names relative to the $path
  1599. * or an empty array if the directory $path is empty,
  1600. * <br />
  1601. * false if $path is not a directory or does not exist.
  1602. * @throws Exception
  1603. * @internal param string $path path to directory to scan.
  1604. */
  1605. private static function listFilesInDirectory($dir, $omitSymlinks, $prefix = '')
  1606. {
  1607. if (!is_dir($dir)) {
  1608. return false;
  1609. }
  1610. $excludes = array(".", "..");
  1611. $result = array();
  1612. $files = self::localScandir($dir);
  1613. if (!$files) {
  1614. return array();
  1615. }
  1616. foreach ($files as $file) {
  1617. if (!in_array($file, $excludes)) {
  1618. $path = $dir . DIRECTORY_SEPARATOR . $file;
  1619. if (is_link($path)) {
  1620. if ($omitSymlinks) {
  1621. continue;
  1622. } else {
  1623. $result[] = $prefix . $file;
  1624. }
  1625. } else if (is_dir($path)) {
  1626. $result[] = $prefix . $file . DIRECTORY_SEPARATOR;
  1627. $subs = elFinderVolumeFTP::listFilesInDirectory($path, $omitSymlinks, $prefix . $file . DIRECTORY_SEPARATOR);
  1628. if ($subs) {
  1629. $result = array_merge($result, $subs);
  1630. }
  1631. } else {
  1632. $result[] = $prefix . $file;
  1633. }
  1634. }
  1635. }
  1636. return $result;
  1637. }
  1638. } // END class