elfinder.drupalfs.driver.inc 17 KB

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