elfinder.drupalfs.driver.inc 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652
  1. <?php
  2. /**
  3. * elFinder Integration
  4. *
  5. * Copyright (c) 2010-2018, Alexey Sukhotin. All rights reserved.
  6. */
  7. /**
  8. * @file
  9. *
  10. * elFinder driver for Drupal filesystem.
  11. *
  12. * @author Alexey Sukhotin
  13. * */
  14. class elFinderVolumeDrupal extends elFinderVolumeLocalFileSystem {
  15. protected $DrupalFilesACL = NULL;
  16. /**
  17. * Create Drupal file object
  18. *
  19. * @param string $path file path
  20. * @return object
  21. * @author Alexey Sukhotin
  22. * */
  23. protected function _drupalfileobject($path) {
  24. $uri = $this->drupalpathtouri($path);
  25. return elfinder_get_drupal_file_obj($uri);
  26. }
  27. /**
  28. * Convert path to Drupal file URI
  29. *
  30. * @param string $path file path
  31. * @return string
  32. * @author Alexey Sukhotin
  33. * */
  34. public function drupalpathtouri($path) {
  35. $pvtpath = drupal_realpath('private://');
  36. $pubpath = drupal_realpath('public://');
  37. $tmppath = drupal_realpath('temporary://');
  38. $uri = '';
  39. if (strpos($path, $pvtpath) === 0) {
  40. $uri = 'private://' . substr($path, strlen($pvtpath) + 1);
  41. } elseif (strpos($path, $tmppath) === 0) {
  42. $uri = 'temporary://' . substr($path, strlen($tmppath) + 1);
  43. } else {
  44. $uri = 'public://' . substr($path, strlen($pubpath) + 1);
  45. }
  46. return @file_stream_wrapper_uri_normalize($uri);
  47. }
  48. /**
  49. * Check if file extension is allowed
  50. *
  51. * @param stdClass $file file object
  52. * @return array
  53. * @author Alexey Sukhotin
  54. **/
  55. protected function CheckExtension(stdClass $file) {
  56. $allowed_extensions = variable_get('elfinder_settings_filesystem_allowed_extensions', '');
  57. if (!empty($allowed_extensions)) {
  58. $errors = file_validate_extensions($file, $allowed_extensions);
  59. if (!empty($errors)) {
  60. $this->setError(strip_tags(implode(' ', $errors)));
  61. return FALSE;
  62. }
  63. }
  64. return TRUE;
  65. }
  66. /**
  67. * Create dir
  68. *
  69. * @param string $path parent dir path
  70. * @param string $name new directory name
  71. * @return bool
  72. * @author Alexey Sukhotin
  73. * */
  74. protected function _mkdir($path, $name) {
  75. $path = $path . DIRECTORY_SEPARATOR . $name;
  76. if (@drupal_mkdir($path)) {
  77. return $path;
  78. }
  79. return FALSE;
  80. }
  81. /**
  82. * Create file
  83. *
  84. * @param string $path parent dir path
  85. * @param string $name new file name
  86. * @return bool
  87. * @author Alexey Sukhotin
  88. * */
  89. protected function _mkfile($path, $name) {
  90. $path = $path . DIRECTORY_SEPARATOR . $name;
  91. $uri = $this->drupalpathtouri($path);
  92. if (!$this->CheckExtension($this->_drupalfileobject($path))) {
  93. return FALSE;
  94. }
  95. $file = file_save_data("", $uri);
  96. $this->FileUsageAdd($file);
  97. if (isset($file->fid)) {
  98. return $path;
  99. }
  100. return FALSE;
  101. }
  102. /**
  103. * Copy file into another file
  104. *
  105. * @param string $source source file path
  106. * @param string $targetDir target directory path
  107. * @param string $name new file name
  108. * @return bool
  109. * @author Alexey Sukhotin
  110. * */
  111. protected function _copy($source, $targetDir, $name) {
  112. $target = $targetDir . DIRECTORY_SEPARATOR . (!empty($name) ? $name : basename($source));
  113. if (!is_dir($target) && !$this->CheckExtension($this->_drupalfileobject($target))) {
  114. return FALSE;
  115. }
  116. if (!$this->CheckUserQuota()) {
  117. return FALSE;
  118. }
  119. if (file_copy($this->_drupalfileobject($source), $this->drupalpathtouri($target))) {
  120. $this->FileUsageAdd($this->_drupalfileobject($target));
  121. return TRUE;
  122. }
  123. return FALSE;
  124. }
  125. /**
  126. * Move file into another parent dir
  127. * Return new file path or false
  128. *
  129. * @param string $source source file path
  130. * @param string $target target dir path
  131. * @param string $name new name
  132. * @return bool|string
  133. * @author Alexey Sukhotin
  134. * */
  135. protected function _move($source, $targetDir, $name) {
  136. $target = $targetDir . DIRECTORY_SEPARATOR . (!empty($name) ? $name : basename($source));
  137. if (!is_dir($target) && !$this->CheckExtension($this->_drupalfileobject($target))) {
  138. return FALSE;
  139. }
  140. if (is_dir($source)) {
  141. $srcuri = $this->drupalpathtouri($source);
  142. $dsturi = $this->drupalpathtouri($target);
  143. $children = db_select('file_managed', 'f')
  144. ->condition('uri', $srcuri . '/%', 'LIKE')
  145. ->fields('f', array('fid', 'uri'))
  146. ->execute()
  147. ->fetchAll();
  148. foreach ($children as $child) {
  149. $newuri = str_replace("$srcuri/", "$dsturi/", $child->uri);
  150. db_update('file_managed')->fields(array('uri' => $newuri))->condition('fid', $child->fid)->execute();
  151. }
  152. return @rename($source, $target);
  153. } elseif (@file_move($this->_drupalfileobject($source), $this->drupalpathtouri($target))) {
  154. return TRUE;
  155. }
  156. return FALSE;
  157. }
  158. /**
  159. * Remove file
  160. *
  161. * @param string $path file path
  162. * @return bool
  163. * @author Alexey Sukhotin
  164. * */
  165. protected function _unlink($path) {
  166. $file = $this->_drupalfileobject($path);
  167. $this->FileUsageDelete($file);
  168. $result = @file_delete($file);
  169. if ($result === TRUE) {
  170. return TRUE;
  171. }
  172. if (is_array($result)) {
  173. return $result['file'];
  174. } else {
  175. return FALSE;
  176. }
  177. }
  178. /**
  179. * Remove dir
  180. *
  181. * @param string $path dir path
  182. * @return bool
  183. * @author Alexey Sukhotin
  184. * */
  185. protected function _rmdir($path) {
  186. return @drupal_rmdir($path);
  187. }
  188. /**
  189. * Delete dirctory trees and included files.
  190. *
  191. * Clone of elfinderVolumeDriver::delTree().
  192. *
  193. * Using elFinderVolumeLocalFileSystem::delTree to delete a folder with files
  194. * in it would not update file_usage and file_managed tables. Using
  195. * elfinderVolumeDriver::delTree makes it work better.
  196. */
  197. protected function delTree($localpath) {
  198. foreach ($this->_scandir($localpath) as $p) {
  199. elFinder::extendTimeLimit();
  200. $stat = $this->stat($this->convEncOut($p));
  201. $this->convEncIn();
  202. ($stat['mime'] === 'directory') ? $this->delTree($p) : $this->_unlink($p);
  203. }
  204. $res = $this->_rmdir($localpath);
  205. $res && $this->clearstatcache();
  206. return $res;
  207. }
  208. /**
  209. * Create new file and write into it from file pointer.
  210. * Return new file path or false on error.
  211. *
  212. * @param resource $fp file pointer
  213. * @param string $dir target dir path
  214. * @param string $name file name
  215. * @return bool|string
  216. * @author Dmitry (dio) Levashov, Alexey Sukhotin
  217. * */
  218. protected function _save($fp, $dir, $name, $stat) {
  219. $tmpname = $name;
  220. $bu_ret = module_invoke_all('elfinder_beforeupload', array('name' => $name, 'dir' => $dir, 'stat' => $stat));
  221. if (isset($bu_ret)) {
  222. if (!is_array($bu_ret)) {
  223. $bu_ret = array($bu_ret);
  224. }
  225. $tmpname = end($bu_ret);
  226. }
  227. $path = $dir . DIRECTORY_SEPARATOR . (!empty($tmpname) ? $tmpname : $name);
  228. if (!$this->CheckUserQuota()) {
  229. return FALSE;
  230. }
  231. if (!$this->CheckFolderCount($dir)) {
  232. return FALSE;
  233. }
  234. if (!$this->CheckExtension($this->_drupalfileobject($path))) {
  235. return FALSE;
  236. }
  237. if (!$this->FileValidate($name)) {
  238. return FALSE;
  239. }
  240. if (!($target = @fopen($path, 'wb'))) {
  241. return FALSE;
  242. }
  243. while (!feof($fp)) {
  244. fwrite($target, fread($fp, 8192));
  245. }
  246. fclose($target);
  247. @chmod($path, $this->options['fileMode']);
  248. $file = $this->_drupalfileobject($path);
  249. @file_save($file);
  250. $this->FileUsageAdd($file);
  251. return $path;
  252. }
  253. protected function CheckUserQuota() {
  254. $space = $this->CalculateUserAllowedSpace();
  255. if ($space == 0) {
  256. $this->setError(t('Quota exceeded'));
  257. return FALSE;
  258. }
  259. return TRUE;
  260. }
  261. protected function CheckFolderCount($dir) {
  262. $max_allowed = variable_get('elfinder_settings_filesystem_maxfilecount', 0);
  263. if ($max_allowed > 0) {
  264. $options = array(
  265. 'recurse' => FALSE,
  266. );
  267. // Match name.extension. This won't count files with no extension.
  268. $files = file_scan_directory($dir, '/.*\..*/', $options);
  269. if (count($files) >= $max_allowed) {
  270. $this->setError(t('Max directory file count of %count reached', array('%count' => $max_allowed)));
  271. return FALSE;
  272. }
  273. }
  274. return TRUE;
  275. }
  276. /**
  277. * Let other Drupal modules perform validation on the uploaded file.
  278. * See hook_file_validate().
  279. *
  280. * @param string $name file name
  281. * @return bool
  282. */
  283. protected function FileValidate($name) {
  284. // The uploaded file is still in temp. Fetch it's name & path from $_FILES.
  285. $index = array_search($name, $_FILES['upload']['name']);
  286. if ($index !== FALSE) {
  287. $file = $this->_drupalfileobject($_FILES['upload']['tmp_name'][$index]);
  288. $validation_errors = module_invoke_all('file_validate', $file);
  289. if (!empty($validation_errors)) {
  290. $this->setError(strip_tags(implode(' ', $validation_errors)));
  291. return FALSE;
  292. }
  293. } else {
  294. watchdog('elfinder', 'File upload "' . $name . '" not found in $_FILES');
  295. }
  296. return TRUE;
  297. }
  298. /**
  299. * Return files list in directory.
  300. *
  301. * @param string $path dir path
  302. * @return array
  303. * @author Dmitry (dio) Levashov
  304. * */
  305. protected function _scandir($path) {
  306. $files = array();
  307. foreach (scandir($path) as $name) {
  308. if ($name != '.' && $name != '..') {
  309. $files[] = $path . DIRECTORY_SEPARATOR . $name;
  310. }
  311. }
  312. return $files;
  313. }
  314. public function owner($target) {
  315. $path = $this->decode($target);
  316. $file = $this->_drupalfileobject($path);
  317. if ($file->fid) {
  318. $owneraccount = user_load($file->uid);
  319. /* AS */
  320. $owner = $owneraccount->name;
  321. $ownerformat = variable_get('elfinder_settings_filesystem_owner_format', '');
  322. if ($ownerformat != '') {
  323. $owner = token_replace($ownerformat, array('user' => $owneraccount));
  324. }
  325. return $owner;
  326. }
  327. return FALSE;
  328. }
  329. public function desc($target, $newdesc = NULL) {
  330. $path = $this->decode($target);
  331. $file = $this->_drupalfileobject($path);
  332. if ($file->fid) {
  333. $finfo = db_select('elfinder_file_extinfo', 'f')
  334. ->condition('fid', $file->fid)
  335. ->fields('f', array('fid', 'description'))
  336. ->execute()
  337. ->fetchObject();
  338. $descobj = new StdClass;
  339. $descobj->fid = $file->fid;
  340. $descobj->description = $newdesc;
  341. if ($newdesc != NULL && user_access('edit file description')) {
  342. if (($rc = drupal_write_record('elfinder_file_extinfo', $descobj, isset($finfo->fid) ? array('fid') : array())) == 0) {
  343. return -1;
  344. }
  345. } else {
  346. return $finfo->description;
  347. }
  348. }
  349. return $newdesc;
  350. }
  351. public function downloadcount($target) {
  352. $path = $this->decode($target);
  353. $file = $this->_drupalfileobject($path);
  354. if ($file->fid && module_exists('elfinder_stats')) {
  355. $downloads = db_select('elfinder_stats', 's')
  356. ->fields('s', array('fid'))
  357. ->condition('s.fid', $file->fid)
  358. ->condition('s.type', 'download')
  359. ->countQuery()
  360. ->execute()
  361. ->fetchField();
  362. return $downloads ? $downloads : 0;
  363. }
  364. return 0;
  365. }
  366. protected function _archive($dir, $files, $name, $arc) {
  367. if (!$this->CheckUserQuota()) {
  368. return FALSE;
  369. }
  370. $ret = parent::_archive($dir, $files, $name, $arc);
  371. if ($ret != FALSE) {
  372. $file = $this->_drupalfileobject($ret);
  373. @file_save($file);
  374. $this->FileUsageAdd($file);
  375. }
  376. return $ret;
  377. }
  378. /**
  379. * Extract files from archive.
  380. *
  381. * Run the parent extract() then add the files to the Drupal db.
  382. *
  383. * @param string $hash
  384. * Archive filename hash.
  385. * @param bool $makedir
  386. * Extract the files into a new folder.
  387. * @return array|bool
  388. */
  389. public function extract($hash, $makedir = NULL) {
  390. if (!$this->CheckUserQuota()) {
  391. return FALSE;
  392. }
  393. $fstat = array();
  394. if ($makedir == NULL) {
  395. $fstat = parent::extract($hash);
  396. } else {
  397. $fstat = parent::extract($hash, $makedir);
  398. }
  399. if ($fstat != FALSE) {
  400. $path = $this->decode($fstat['hash']);
  401. $this->AddToDrupalDB($path);
  402. $file = $this->_drupalfileobject($path);
  403. if ($fstat['mime'] !== 'directory') {
  404. $this->FileUsageAdd($file);
  405. }
  406. }
  407. return $fstat;
  408. }
  409. /**
  410. * Recursive function to add new files to Drupal's db.
  411. *
  412. * TODO: If a file with the same name already exists anywhere else, this will
  413. * not create a new entry.
  414. */
  415. protected function AddToDrupalDB($files) {
  416. foreach($files AS $file) {
  417. if($file['mime'] == 'directory') {
  418. $newfiles = $this->scandir($file['hash']);
  419. $this->AddToDrupalDB($newfiles);
  420. } else {
  421. $filepath = $this->decode($file['hash']);
  422. $file_object = $this->_drupalfileobject($filepath);
  423. @file_save($file_object);
  424. $this->FileUsageAdd($file_object);
  425. }
  426. }
  427. return TRUE;
  428. }
  429. protected function CalculateUserAllowedSpace($checkuser = NULL) {
  430. global $user;
  431. $realUser = isset($checkuser) ? $checkuser : $user;
  432. $currentSpace = $this->CalculateUserUsedSpace($realUser);
  433. $maxSpace = isset($this->options['userProfile']->settings['user_quota']) ? parse_size($this->options['userProfile']->settings['user_quota']) : NULL;
  434. $diff = $maxSpace - $currentSpace;
  435. if (isset($maxSpace) && $maxSpace > 0) {
  436. if ($diff > 0) {
  437. return $diff;
  438. } else {
  439. return 0;
  440. }
  441. }
  442. return -1;
  443. }
  444. protected function CalculateUserUsedSpace($checkuser = NULL) {
  445. global $user;
  446. $realUser = isset($checkuser) ? $checkuser : $user;
  447. $q = db_query("SELECT sum(filesize) FROM {file_managed} WHERE uid = :uid", array(':uid' => $realUser->uid));
  448. $result = $q->fetchField();
  449. return $result;
  450. }
  451. protected function FileUsageAdd($file) {
  452. // Record that the module elfinder is using the file.
  453. @file_usage_add($file, 'elfinder', 'elfinderFileFetcher', 0); // 0 : means that there is no reference at the moment.
  454. }
  455. protected function FileUsageDelete($file) {
  456. // Delete record that the module elfinder is using the file.
  457. @file_usage_delete($file, 'elfinder', 'elfinderFileFetcher', 0); // 0 : means that there is no reference at the moment.
  458. }
  459. protected function _checkArchivers() {
  460. $this->archivers = variable_get('elfinder_settings_misc_archivers', array());
  461. if (count($this->archivers) == 0) {
  462. parent::_checkArchivers();
  463. variable_set('elfinder_settings_misc_archivers', $this->archivers);
  464. }
  465. }
  466. /**
  467. * Rename file and return file info
  468. *
  469. * @param string $hash file hash
  470. * @param string $name new file name
  471. * @return array|false
  472. **/
  473. public function rename($hash, $name) {
  474. $results = parent::rename($hash, $name);
  475. // Update any fields that point to this file.
  476. field_cache_clear();
  477. return $results;
  478. }
  479. /**
  480. * Taken from elFinderVolumeDriver::remove().
  481. *
  482. * Adds a message if the file is in use.
  483. */
  484. protected function remove($path, $force = false) {
  485. $stat = $this->stat($path);
  486. if (empty($stat)) {
  487. return $this->setError(elFinder::ERROR_RM, $path, elFinder::ERROR_FILE_NOT_FOUND);
  488. }
  489. $stat['realpath'] = $path;
  490. $this->rmTmb($stat);
  491. $this->clearcache();
  492. if (!$force && !empty($stat['locked'])) {
  493. return $this->setError(elFinder::ERROR_LOCKED, $this->path($stat['hash']));
  494. }
  495. if ($stat['mime'] == 'directory' && empty($stat['thash'])) {
  496. $ret = $this->delTree($this->convEncIn($path));
  497. $this->convEncOut();
  498. if (!$ret) {
  499. return $this->setError(elFinder::ERROR_RM, $this->path($stat['hash']));
  500. }
  501. } else {
  502. $results = $this->_unlink($this->convEncIn($path));
  503. if (!$results) {
  504. return $this->setError(elFinder::ERROR_RM, $this->path($stat['hash']));
  505. }
  506. if (is_array($results)) {
  507. // File is in use and is being protected by Drupal. Fetch the first
  508. // entity where it's used.
  509. foreach($results AS $entity_type => $entity) {
  510. if(is_array($entity)) {
  511. foreach($entity AS $id => $count) {
  512. if($entity_type == 'node' && is_integer($id)) {
  513. $node = node_load($id);
  514. if(!empty($node->title)) {
  515. return $this->setError(elFinder::ERROR_RM, $this->path($stat['hash']), '', t('File is used in @title', array('@title' => $node->title)));
  516. }
  517. }
  518. }
  519. }
  520. }
  521. return $this->setError(elFinder::ERROR_RM, $this->path($stat['hash']), t('File is in use.'));
  522. }
  523. $this->clearstatcache();
  524. }
  525. $this->removed[] = $stat;
  526. return true;
  527. }
  528. }