elFinderVolumeFTP.class.php 56 KB

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