elFinderVolumeBox.class.php 60 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972
  1. <?php
  2. /**
  3. * Simple elFinder driver for BoxDrive
  4. * Box.com API v2.0.
  5. *
  6. * @author Dmitry (dio) Levashov
  7. * @author Cem (discofever)
  8. **/
  9. class elFinderVolumeBox extends elFinderVolumeDriver
  10. {
  11. /**
  12. * Driver id
  13. * Must be started from letter and contains [a-z0-9]
  14. * Used as part of volume id.
  15. *
  16. * @var string
  17. **/
  18. protected $driverId = 'bd';
  19. /**
  20. * @var string The base URL for API requests
  21. */
  22. const API_URL = 'https://api.box.com/2.0';
  23. /**
  24. * @var string The base URL for authorization requests
  25. */
  26. const AUTH_URL = 'https://account.box.com/api/oauth2/authorize';
  27. /**
  28. * @var string The base URL for token requests
  29. */
  30. const TOKEN_URL = 'https://api.box.com/oauth2/token';
  31. /**
  32. * @var string The base URL for upload requests
  33. */
  34. const UPLOAD_URL = 'https://upload.box.com/api/2.0';
  35. /**
  36. * Fetch fields list.
  37. *
  38. * @var string
  39. */
  40. const FETCHFIELDS = 'type,id,name,created_at,modified_at,description,size,parent,permissions,file_version,shared_link';
  41. /**
  42. * Box.com token object.
  43. *
  44. * @var object
  45. **/
  46. protected $token = null;
  47. /**
  48. * Directory for tmp files
  49. * If not set driver will try to use tmbDir as tmpDir.
  50. *
  51. * @var string
  52. **/
  53. protected $tmp = '';
  54. /**
  55. * Net mount key.
  56. *
  57. * @var string
  58. **/
  59. public $netMountKey = '';
  60. /**
  61. * Thumbnail prefix.
  62. *
  63. * @var string
  64. **/
  65. private $tmbPrefix = '';
  66. /**
  67. * Path to access token file for permanent mount
  68. *
  69. * @var string
  70. */
  71. private $aTokenFile = '';
  72. /**
  73. * hasCache by folders.
  74. *
  75. * @var array
  76. **/
  77. protected $HasdirsCache = array();
  78. /**
  79. * Constructor
  80. * Extend options with required fields.
  81. *
  82. * @author Dmitry (dio) Levashov
  83. * @author Cem (DiscoFever)
  84. **/
  85. public function __construct()
  86. {
  87. $opts = array(
  88. 'client_id' => '',
  89. 'client_secret' => '',
  90. 'accessToken' => '',
  91. 'root' => 'Box.com',
  92. 'path' => '/',
  93. 'separator' => '/',
  94. 'tmbPath' => '',
  95. 'tmbURL' => '',
  96. 'tmpPath' => '',
  97. 'acceptedName' => '#^[^\\\/]+$#',
  98. 'rootCssClass' => 'elfinder-navbar-root-box',
  99. );
  100. $this->options = array_merge($this->options, $opts);
  101. $this->options['mimeDetect'] = 'internal';
  102. }
  103. /*********************************************************************/
  104. /* ORIGINAL FUNCTIONS */
  105. /*********************************************************************/
  106. /**
  107. * Get Parent ID, Item ID, Parent Path as an array from path.
  108. *
  109. * @param string $path
  110. *
  111. * @return array
  112. */
  113. protected function _bd_splitPath($path)
  114. {
  115. $path = trim($path, '/');
  116. $pid = '';
  117. if ($path === '') {
  118. $id = '0';
  119. $parent = '';
  120. } else {
  121. $paths = explode('/', trim($path, '/'));
  122. $id = array_pop($paths);
  123. if ($paths) {
  124. $parent = '/' . implode('/', $paths);
  125. $pid = array_pop($paths);
  126. } else {
  127. $pid = '0';
  128. $parent = '/';
  129. }
  130. }
  131. return array($pid, $id, $parent);
  132. }
  133. /**
  134. * Obtains a new access token from OAuth. This token is valid for one hour.
  135. *
  136. * @param string $clientSecret The Box client secret
  137. * @param string $code The code returned by Box after
  138. * successful log in
  139. * @param string $redirectUri Must be the same as the redirect URI passed
  140. * to LoginUrl
  141. *
  142. * @return bool|object
  143. * @throws \Exception Thrown if this Client instance's clientId is not set
  144. * @throws \Exception Thrown if the redirect URI of this Client instance's
  145. * state is not set
  146. */
  147. protected function _bd_obtainAccessToken($client_id, $client_secret, $code)
  148. {
  149. if (null === $client_id) {
  150. return $this->setError('The client ID must be set to call obtainAccessToken()');
  151. }
  152. if (null === $client_secret) {
  153. return $this->setError('The client Secret must be set to call obtainAccessToken()');
  154. }
  155. if (null === $code) {
  156. return $this->setError('Authorization code must be set to call obtainAccessToken()');
  157. }
  158. $url = self::TOKEN_URL;
  159. $curl = curl_init();
  160. $fields = http_build_query(
  161. array(
  162. 'client_id' => $client_id,
  163. 'client_secret' => $client_secret,
  164. 'code' => $code,
  165. 'grant_type' => 'authorization_code',
  166. )
  167. );
  168. curl_setopt_array($curl, array(
  169. // General options.
  170. CURLOPT_RETURNTRANSFER => true,
  171. CURLOPT_POST => true,
  172. CURLOPT_POSTFIELDS => $fields,
  173. CURLOPT_URL => $url,
  174. ));
  175. $decoded = $this->_bd_curlExec($curl, true, array('Content-Length: ' . strlen($fields)));
  176. $res = (object)array(
  177. 'expires' => time() + $decoded->expires_in - 30,
  178. 'initialToken' => '',
  179. 'data' => $decoded
  180. );
  181. if (!empty($decoded->refresh_token)) {
  182. $res->initialToken = md5($client_id . $decoded->refresh_token);
  183. }
  184. return $res;
  185. }
  186. /**
  187. * Get token and auto refresh.
  188. *
  189. * @return true|string error message
  190. * @throws Exception
  191. */
  192. protected function _bd_refreshToken()
  193. {
  194. if (!property_exists($this->token, 'expires') || $this->token->expires < time()) {
  195. if (!$this->options['client_id']) {
  196. $this->options['client_id'] = ELFINDER_BOX_CLIENTID;
  197. }
  198. if (!$this->options['client_secret']) {
  199. $this->options['client_secret'] = ELFINDER_BOX_CLIENTSECRET;
  200. }
  201. if (empty($this->token->data->refresh_token)) {
  202. throw new \Exception(elFinder::ERROR_REAUTH_REQUIRE);
  203. } else {
  204. $refresh_token = $this->token->data->refresh_token;
  205. $initialToken = $this->_bd_getInitialToken();
  206. }
  207. $lock = '';
  208. $aTokenFile = $this->aTokenFile? $this->aTokenFile : $this->_bd_getATokenFile();
  209. if ($aTokenFile && is_file($aTokenFile)) {
  210. $lock = $aTokenFile . '.lock';
  211. if (file_exists($lock)) {
  212. // Probably updating on other instance
  213. return true;
  214. }
  215. touch($lock);
  216. $GLOBALS['elFinderTempFiles'][$lock] = true;
  217. }
  218. $postData = array(
  219. 'client_id' => $this->options['client_id'],
  220. 'client_secret' => $this->options['client_secret'],
  221. 'grant_type' => 'refresh_token',
  222. 'refresh_token' => $refresh_token
  223. );
  224. $url = self::TOKEN_URL;
  225. $curl = curl_init();
  226. curl_setopt_array($curl, array(
  227. // General options.
  228. CURLOPT_RETURNTRANSFER => true,
  229. CURLOPT_POST => true, // i am sending post data
  230. CURLOPT_POSTFIELDS => http_build_query($postData),
  231. CURLOPT_URL => $url,
  232. ));
  233. $decoded = $error = '';
  234. try {
  235. $decoded = $this->_bd_curlExec($curl, true, array(), $postData);
  236. } catch (Exception $e) {
  237. $error = $e->getMessage();
  238. }
  239. if (!$decoded && !$error) {
  240. $error = 'Tried to renew the access token, but did not get a response from the Box server.';
  241. }
  242. if ($error) {
  243. $lock && unlink($lock);
  244. throw new \Exception('Box access token update failed. ('.$error.') If this message appears repeatedly, please notify the administrator.');
  245. }
  246. if (empty($decoded->access_token)) {
  247. if ($aTokenFile) {
  248. if (is_file($aTokenFile)) {
  249. unlink($aTokenFile);
  250. }
  251. }
  252. $err = property_exists($decoded, 'error')? ' ' . $decoded->error : '';
  253. $err .= property_exists($decoded, 'error_description')? ' ' . $decoded->error_description : '';
  254. throw new \Exception($err? $err : elFinder::ERROR_REAUTH_REQUIRE);
  255. }
  256. $token = (object)array(
  257. 'expires' => time() + $decoded->expires_in - 300,
  258. 'initialToken' => $initialToken,
  259. 'data' => $decoded,
  260. );
  261. $this->token = $token;
  262. $json = json_encode($token);
  263. if (!empty($decoded->refresh_token)) {
  264. if (empty($this->options['netkey']) && $aTokenFile) {
  265. file_put_contents($aTokenFile, json_encode($token), LOCK_EX);
  266. $this->options['accessToken'] = $json;
  267. } else if (!empty($this->options['netkey'])) {
  268. // OAuth2 refresh token can be used only once,
  269. // so update it if it is the same as the token file
  270. if ($aTokenFile && is_file($aTokenFile)) {
  271. if ($_token = json_decode(file_get_contents($aTokenFile))) {
  272. if ($_token->data->refresh_token === $refresh_token) {
  273. file_put_contents($aTokenFile, $json, LOCK_EX);
  274. }
  275. }
  276. }
  277. $this->options['accessToken'] = $json;
  278. // update session value
  279. elFinder::$instance->updateNetVolumeOption($this->options['netkey'], 'accessToken', $json);
  280. $this->session->set('BoxTokens', $token);
  281. } else {
  282. throw new \Exception(ERROR_CREATING_TEMP_DIR);
  283. }
  284. }
  285. $lock && unlink($lock);
  286. }
  287. return true;
  288. }
  289. /**
  290. * Creates a base cURL object which is compatible with the Box.com API.
  291. *
  292. * @param array $options cURL options
  293. *
  294. * @return resource A compatible cURL object
  295. */
  296. protected function _bd_prepareCurl($options = array())
  297. {
  298. $curl = curl_init();
  299. $defaultOptions = array(
  300. // General options.
  301. CURLOPT_RETURNTRANSFER => true,
  302. );
  303. curl_setopt_array($curl, $options + $defaultOptions);
  304. return $curl;
  305. }
  306. /**
  307. * Creates a base cURL object which is compatible with the Box.com API.
  308. *
  309. * @param $url
  310. * @param bool $contents
  311. *
  312. * @return boolean|array
  313. * @throws Exception
  314. */
  315. protected function _bd_fetch($url, $contents = false)
  316. {
  317. $curl = curl_init($url);
  318. curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
  319. if ($contents) {
  320. return $this->_bd_curlExec($curl, false);
  321. } else {
  322. $result = $this->_bd_curlExec($curl);
  323. if (isset($result->entries)) {
  324. $res = $result->entries;
  325. $cnt = count($res);
  326. $total = $result->total_count;
  327. $offset = $result->offset;
  328. $single = ($result->limit == 1) ? true : false;
  329. if (!$single && $total > ($offset + $cnt)) {
  330. $offset = $offset + $cnt;
  331. if (strpos($url, 'offset=') === false) {
  332. $url .= '&offset=' . $offset;
  333. } else {
  334. $url = preg_replace('/^(.+?offset=)\d+(.*)$/', '${1}' . $offset . '$2', $url);
  335. }
  336. $more = $this->_bd_fetch($url);
  337. if (is_array($more)) {
  338. $res = array_merge($res, $more);
  339. }
  340. }
  341. return $res;
  342. } else {
  343. if (isset($result->type) && $result->type === 'error') {
  344. return false;
  345. } else {
  346. return $result;
  347. }
  348. }
  349. }
  350. }
  351. /**
  352. * Call curl_exec().
  353. *
  354. * @param resource $curl
  355. * @param bool|string $decodeOrParent
  356. * @param array $headers
  357. *
  358. * @throws \Exception
  359. * @return mixed
  360. */
  361. protected function _bd_curlExec($curl, $decodeOrParent = true, $headers = array(), $postData = array())
  362. {
  363. if ($this->token) {
  364. $headers = array_merge(array(
  365. 'Authorization: Bearer ' . $this->token->data->access_token,
  366. ), $headers);
  367. }
  368. $result = elFinder::curlExec($curl, array(), $headers, $postData);
  369. if (!$decodeOrParent) {
  370. return $result;
  371. }
  372. $decoded = json_decode($result);
  373. if ($error = !empty($decoded->error_code)) {
  374. $errmsg = $decoded->error_code;
  375. if (!empty($decoded->message)) {
  376. $errmsg .= ': ' . $decoded->message;
  377. }
  378. throw new \Exception($errmsg);
  379. } else if ($error = !empty($decoded->error)) {
  380. $errmsg = $decoded->error;
  381. if (!empty($decoded->error_description)) {
  382. $errmsg .= ': ' . $decoded->error_description;
  383. }
  384. throw new \Exception($errmsg);
  385. }
  386. // make catch
  387. if ($decodeOrParent && $decodeOrParent !== true) {
  388. $raws = null;
  389. if (isset($decoded->entries)) {
  390. $raws = $decoded->entries;
  391. } elseif (isset($decoded->id)) {
  392. $raws = array($decoded);
  393. }
  394. if ($raws) {
  395. foreach ($raws as $raw) {
  396. if (isset($raw->id)) {
  397. $stat = $this->_bd_parseRaw($raw);
  398. $itemPath = $this->_joinPath($decodeOrParent, $raw->id);
  399. $this->updateCache($itemPath, $stat);
  400. }
  401. }
  402. }
  403. }
  404. return $decoded;
  405. }
  406. /**
  407. * Drive query and fetchAll.
  408. *
  409. * @param $itemId
  410. * @param bool $fetch_self
  411. * @param bool $recursive
  412. *
  413. * @return bool|object
  414. * @throws Exception
  415. */
  416. protected function _bd_query($itemId, $fetch_self = false, $recursive = false)
  417. {
  418. $result = [];
  419. if (null === $itemId) {
  420. $itemId = '0';
  421. }
  422. if ($fetch_self) {
  423. $path = '/folders/' . $itemId . '?fields=' . self::FETCHFIELDS;
  424. } else {
  425. $path = '/folders/' . $itemId . '/items?limit=1000&fields=' . self::FETCHFIELDS;
  426. }
  427. $url = self::API_URL . $path;
  428. if ($recursive) {
  429. foreach ($this->_bd_fetch($url) as $file) {
  430. if ($file->type == 'folder') {
  431. $result[] = $file;
  432. $result = array_merge($result, $this->_bd_query($file->id, $fetch_self = false, $recursive = true));
  433. } elseif ($file->type == 'file') {
  434. $result[] = $file;
  435. }
  436. }
  437. } else {
  438. $result = $this->_bd_fetch($url);
  439. if ($fetch_self && !$result) {
  440. $path = '/files/' . $itemId . '?fields=' . self::FETCHFIELDS;
  441. $url = self::API_URL . $path;
  442. $result = $this->_bd_fetch($url);
  443. }
  444. }
  445. return $result;
  446. }
  447. /**
  448. * Get dat(box metadata) from Box.com.
  449. *
  450. * @param string $path
  451. *
  452. * @return object box metadata
  453. * @throws Exception
  454. */
  455. protected function _bd_getRawItem($path)
  456. {
  457. if ($path == '/') {
  458. return $this->_bd_query('0', $fetch_self = true);
  459. }
  460. list(, $itemId) = $this->_bd_splitPath($path);
  461. try {
  462. return $this->_bd_query($itemId, $fetch_self = true);
  463. } catch (Exception $e) {
  464. $empty = new stdClass;
  465. return $empty;
  466. }
  467. }
  468. /**
  469. * Parse line from box metadata output and return file stat (array).
  470. *
  471. * @param object $raw line from ftp_rawlist() output
  472. *
  473. * @return array
  474. * @author Dmitry Levashov
  475. **/
  476. protected function _bd_parseRaw($raw)
  477. {
  478. $stat = array();
  479. $stat['rev'] = isset($raw->id) ? $raw->id : 'root';
  480. $stat['name'] = $raw->name;
  481. if (!empty($raw->modified_at)) {
  482. $stat['ts'] = strtotime($raw->modified_at);
  483. }
  484. if ($raw->type === 'folder') {
  485. $stat['mime'] = 'directory';
  486. $stat['size'] = 0;
  487. $stat['dirs'] = -1;
  488. } else {
  489. $stat['size'] = (int)$raw->size;
  490. if (!empty($raw->shared_link->url) && $raw->shared_link->access == 'open') {
  491. if ($url = $this->getSharedWebContentLink($raw)) {
  492. $stat['url'] = $url;
  493. }
  494. } elseif (!$this->disabledGetUrl) {
  495. $stat['url'] = '1';
  496. }
  497. }
  498. return $stat;
  499. }
  500. /**
  501. * Get thumbnail from Box.com.
  502. *
  503. * @param string $path
  504. * @param string $size
  505. *
  506. * @return string | boolean
  507. */
  508. protected function _bd_getThumbnail($path)
  509. {
  510. list(, $itemId) = $this->_bd_splitPath($path);
  511. try {
  512. $url = self::API_URL . '/files/' . $itemId . '/thumbnail.png?min_height=' . $this->tmbSize . '&min_width=' . $this->tmbSize;
  513. $contents = $this->_bd_fetch($url, true);
  514. return $contents;
  515. } catch (Exception $e) {
  516. return false;
  517. }
  518. }
  519. /**
  520. * Remove item.
  521. *
  522. * @param string $path file path
  523. *
  524. * @return bool
  525. **/
  526. protected function _bd_unlink($path, $type = null)
  527. {
  528. try {
  529. list(, $itemId) = $this->_bd_splitPath($path);
  530. if ($type == 'folders') {
  531. $url = self::API_URL . '/' . $type . '/' . $itemId . '?recursive=true';
  532. } else {
  533. $url = self::API_URL . '/' . $type . '/' . $itemId;
  534. }
  535. $curl = $this->_bd_prepareCurl(array(
  536. CURLOPT_URL => $url,
  537. CURLOPT_CUSTOMREQUEST => 'DELETE',
  538. ));
  539. //unlink or delete File or Folder in the Parent
  540. $this->_bd_curlExec($curl);
  541. } catch (Exception $e) {
  542. return $this->setError('Box error: ' . $e->getMessage());
  543. }
  544. return true;
  545. }
  546. /**
  547. * Get AccessToken file path
  548. *
  549. * @return string ( description_of_the_return_value )
  550. */
  551. protected function _bd_getATokenFile()
  552. {
  553. $tmp = $aTokenFile = '';
  554. if (!empty($this->token->data->refresh_token)) {
  555. if (!$this->tmp) {
  556. $tmp = elFinder::getStaticVar('commonTempPath');
  557. if (!$tmp) {
  558. $tmp = $this->getTempPath();
  559. }
  560. $this->tmp = $tmp;
  561. }
  562. if ($tmp) {
  563. $aTokenFile = $tmp . DIRECTORY_SEPARATOR . $this->_bd_getInitialToken() . '.btoken';
  564. }
  565. }
  566. return $aTokenFile;
  567. }
  568. /**
  569. * Get Initial Token (MD5 hash)
  570. *
  571. * @return string
  572. */
  573. protected function _bd_getInitialToken()
  574. {
  575. return (empty($this->token->initialToken)? md5($this->options['client_id'] . (!empty($this->token->data->refresh_token)? $this->token->data->refresh_token : $this->token->data->access_token)) : $this->token->initialToken);
  576. }
  577. /*********************************************************************/
  578. /* OVERRIDE FUNCTIONS */
  579. /*********************************************************************/
  580. /**
  581. * Prepare
  582. * Call from elFinder::netmout() before volume->mount().
  583. *
  584. * @return array
  585. * @author Naoki Sawada
  586. * @author Raja Sharma updating for Box
  587. **/
  588. public function netmountPrepare($options)
  589. {
  590. if (empty($options['client_id']) && defined('ELFINDER_BOX_CLIENTID')) {
  591. $options['client_id'] = ELFINDER_BOX_CLIENTID;
  592. }
  593. if (empty($options['client_secret']) && defined('ELFINDER_BOX_CLIENTSECRET')) {
  594. $options['client_secret'] = ELFINDER_BOX_CLIENTSECRET;
  595. }
  596. if (isset($options['pass']) && $options['pass'] === 'reauth') {
  597. $options['user'] = 'init';
  598. $options['pass'] = '';
  599. $this->session->remove('BoxTokens');
  600. }
  601. if (isset($options['id'])) {
  602. $this->session->set('nodeId', $options['id']);
  603. } else if ($_id = $this->session->get('nodeId')) {
  604. $options['id'] = $_id;
  605. $this->session->set('nodeId', $_id);
  606. }
  607. if (!empty($options['tmpPath'])) {
  608. if ((is_dir($options['tmpPath']) || mkdir($this->options['tmpPath'])) && is_writable($options['tmpPath'])) {
  609. $this->tmp = $options['tmpPath'];
  610. }
  611. }
  612. try {
  613. if (empty($options['client_id']) || empty($options['client_secret'])) {
  614. return array('exit' => true, 'body' => '{msg:errNetMountNoDriver}');
  615. }
  616. $itpCare = isset($options['code']);
  617. $code = $itpCare? $options['code'] : (isset($_GET['code'])? $_GET['code'] : '');
  618. if ($code) {
  619. try {
  620. if (!empty($options['id'])) {
  621. // Obtain the token using the code received by the Box.com API
  622. $this->session->set('BoxTokens',
  623. $this->_bd_obtainAccessToken($options['client_id'], $options['client_secret'], $code));
  624. $out = array(
  625. 'node' => $options['id'],
  626. 'json' => '{"protocol": "box", "mode": "done", "reset": 1}',
  627. 'bind' => 'netmount'
  628. );
  629. } else {
  630. $nodeid = ($_GET['host'] === '1')? 'elfinder' : $_GET['host'];
  631. $out = array(
  632. 'node' => $nodeid,
  633. 'json' => json_encode(array(
  634. 'protocol' => 'box',
  635. 'host' => $nodeid,
  636. 'mode' => 'redirect',
  637. 'options' => array(
  638. 'id' => $nodeid,
  639. 'code'=> $code
  640. )
  641. )),
  642. 'bind' => 'netmount'
  643. );
  644. }
  645. if (!$itpCare) {
  646. return array('exit' => 'callback', 'out' => $out);
  647. } else {
  648. return array('exit' => true, 'body' => $out['json']);
  649. }
  650. } catch (Exception $e) {
  651. $out = array(
  652. 'node' => $options['id'],
  653. 'json' => json_encode(array('error' => $e->getMessage())),
  654. );
  655. return array('exit' => 'callback', 'out' => $out);
  656. }
  657. } elseif (!empty($_GET['error'])) {
  658. $out = array(
  659. 'node' => $options['id'],
  660. 'json' => json_encode(array('error' => elFinder::ERROR_ACCESS_DENIED)),
  661. );
  662. return array('exit' => 'callback', 'out' => $out);
  663. }
  664. if ($options['user'] === 'init') {
  665. $this->token = $this->session->get('BoxTokens');
  666. if ($this->token) {
  667. try {
  668. $this->_bd_refreshToken();
  669. } catch (Exception $e) {
  670. $this->setError($e->getMessage());
  671. $this->token = null;
  672. $this->session->remove('BoxTokens');
  673. }
  674. }
  675. if (empty($this->token)) {
  676. $result = false;
  677. } else {
  678. $path = $options['path'];
  679. if ($path === '/' || $path === 'root') {
  680. $path = '0';
  681. }
  682. $result = $this->_bd_query($path, $fetch_self = false, $recursive = false);
  683. }
  684. if ($result === false) {
  685. $redirect = elFinder::getConnectorUrl();
  686. $redirect .= (strpos($redirect, '?') !== false? '&' : '?') . 'cmd=netmount&protocol=box&host=' . ($options['id'] === 'elfinder'? '1' : $options['id']);
  687. try {
  688. $this->session->set('BoxTokens', (object)array('token' => null));
  689. $url = self::AUTH_URL . '?' . http_build_query(array('response_type' => 'code', 'client_id' => $options['client_id'], 'redirect_uri' => $redirect));
  690. } catch (Exception $e) {
  691. return array('exit' => true, 'body' => '{msg:errAccess}');
  692. }
  693. $html = '<input id="elf-volumedriver-box-host-btn" class="ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only" value="{msg:btnApprove}" type="button">';
  694. $html .= '<script>
  695. $("#' . $options['id'] . '").elfinder("instance").trigger("netmount", {protocol: "box", mode: "makebtn", url: "' . $url . '"});
  696. </script>';
  697. return array('exit' => true, 'body' => $html);
  698. } else {
  699. $folders = [];
  700. if ($result) {
  701. foreach ($result as $res) {
  702. if ($res->type == 'folder') {
  703. $folders[$res->id . ' '] = $res->name;
  704. }
  705. }
  706. natcasesort($folders);
  707. }
  708. if ($options['pass'] === 'folders') {
  709. return ['exit' => true, 'folders' => $folders];
  710. }
  711. $folders = ['root' => 'My Box'] + $folders;
  712. $folders = json_encode($folders);
  713. $expires = empty($this->token->data->refresh_token) ? (int)$this->token->expires : 0;
  714. $mnt2res = empty($this->token->data->refresh_token) ? '' : ', "mnt2res": 1';
  715. $json = '{"protocol": "box", "mode": "done", "folders": ' . $folders . ', "expires": ' . $expires . $mnt2res . '}';
  716. $html = 'Box.com';
  717. $html .= '<script>
  718. $("#' . $options['id'] . '").elfinder("instance").trigger("netmount", ' . $json . ');
  719. </script>';
  720. return array('exit' => true, 'body' => $html);
  721. }
  722. }
  723. } catch (Exception $e) {
  724. return array('exit' => true, 'body' => '{msg:errNetMountNoDriver}');
  725. }
  726. if ($_aToken = $this->session->get('BoxTokens')) {
  727. $options['accessToken'] = json_encode($_aToken);
  728. if ($this->options['path'] === 'root' || !$this->options['path']) {
  729. $this->options['path'] = '/';
  730. }
  731. } else {
  732. $this->session->remove('BoxTokens');
  733. $this->setError(elFinder::ERROR_NETMOUNT, $options['host'], implode(' ', $this->error()));
  734. return array('exit' => true, 'error' => $this->error());
  735. }
  736. $this->session->remove('nodeId');
  737. unset($options['user'], $options['pass'], $options['id']);
  738. return $options;
  739. }
  740. /**
  741. * process of on netunmount
  742. * Drop `box` & rm thumbs.
  743. *
  744. * @param $netVolumes
  745. * @param $key
  746. *
  747. * @return bool
  748. */
  749. public function netunmount($netVolumes, $key)
  750. {
  751. if ($tmbs = glob(rtrim($this->options['tmbPath'], '\\/') . DIRECTORY_SEPARATOR . $this->tmbPrefix . '*.png')) {
  752. foreach ($tmbs as $file) {
  753. unlink($file);
  754. }
  755. }
  756. return true;
  757. }
  758. /**
  759. * Return debug info for client.
  760. *
  761. * @return array
  762. **/
  763. public function debug()
  764. {
  765. $res = parent::debug();
  766. if (!empty($this->options['netkey']) && !empty($this->options['accessToken'])) {
  767. $res['accessToken'] = $this->options['accessToken'];
  768. }
  769. return $res;
  770. }
  771. /*********************************************************************/
  772. /* INIT AND CONFIGURE */
  773. /*********************************************************************/
  774. /**
  775. * Prepare FTP connection
  776. * Connect to remote server and check if credentials are correct, if so, store the connection id in $ftp_conn.
  777. *
  778. * @return bool
  779. * @throws Exception
  780. * @author Dmitry (dio) Levashov
  781. * @author Cem (DiscoFever)
  782. */
  783. protected function init()
  784. {
  785. if (!$this->options['accessToken']) {
  786. return $this->setError('Required option `accessToken` is undefined.');
  787. }
  788. if (!empty($this->options['tmpPath'])) {
  789. if ((is_dir($this->options['tmpPath']) || mkdir($this->options['tmpPath'])) && is_writable($this->options['tmpPath'])) {
  790. $this->tmp = $this->options['tmpPath'];
  791. }
  792. }
  793. $error = false;
  794. try {
  795. $this->token = json_decode($this->options['accessToken']);
  796. if (!is_object($this->token)) {
  797. throw new Exception('Required option `accessToken` is invalid JSON.');
  798. }
  799. // make net mount key
  800. if (empty($this->options['netkey'])) {
  801. $this->netMountKey = $this->_bd_getInitialToken();
  802. } else {
  803. $this->netMountKey = $this->options['netkey'];
  804. }
  805. if ($this->aTokenFile = $this->_bd_getATokenFile()) {
  806. if (empty($this->options['netkey'])) {
  807. if ($this->aTokenFile) {
  808. if (is_file($this->aTokenFile)) {
  809. $this->token = json_decode(file_get_contents($this->aTokenFile));
  810. if (!is_object($this->token)) {
  811. unlink($this->aTokenFile);
  812. throw new Exception('Required option `accessToken` is invalid JSON.');
  813. }
  814. } else {
  815. file_put_contents($this->aTokenFile, json_encode($this->token), LOCK_EX);
  816. }
  817. }
  818. } else if (is_file($this->aTokenFile)) {
  819. // If the refresh token is the same as the permanent volume
  820. $this->token = json_decode(file_get_contents($this->aTokenFile));
  821. }
  822. }
  823. $this->needOnline && $this->_bd_refreshToken();
  824. } catch (Exception $e) {
  825. $this->token = null;
  826. $error = true;
  827. $this->setError($e->getMessage());
  828. }
  829. if ($this->netMountKey) {
  830. $this->tmbPrefix = 'box' . base_convert($this->netMountKey, 16, 32);
  831. }
  832. if ($error) {
  833. if (empty($this->options['netkey']) && $this->tmbPrefix) {
  834. // for delete thumbnail
  835. $this->netunmount(null, null);
  836. }
  837. return false;
  838. }
  839. // normalize root path
  840. if ($this->options['path'] == 'root') {
  841. $this->options['path'] = '/';
  842. }
  843. $this->root = $this->options['path'] = $this->_normpath($this->options['path']);
  844. $this->options['root'] = ($this->options['root'] == '')? 'Box.com' : $this->options['root'];
  845. if (empty($this->options['alias'])) {
  846. if ($this->needOnline) {
  847. list(, $itemId) = $this->_bd_splitPath($this->options['path']);
  848. $this->options['alias'] = ($this->options['path'] === '/') ? $this->options['root'] :
  849. $this->_bd_query($itemId, $fetch_self = true)->name . '@Box';
  850. if (!empty($this->options['netkey'])) {
  851. elFinder::$instance->updateNetVolumeOption($this->options['netkey'], 'alias', $this->options['alias']);
  852. }
  853. } else {
  854. $this->options['alias'] = $this->options['root'];
  855. }
  856. }
  857. $this->rootName = $this->options['alias'];
  858. // This driver dose not support `syncChkAsTs`
  859. $this->options['syncChkAsTs'] = false;
  860. // 'lsPlSleep' minmum 10 sec
  861. $this->options['lsPlSleep'] = max(10, $this->options['lsPlSleep']);
  862. // enable command archive
  863. $this->options['useRemoteArchive'] = true;
  864. return true;
  865. }
  866. /**
  867. * Configure after successfull mount.
  868. *
  869. * @author Dmitry (dio) Levashov
  870. * @throws elFinderAbortException
  871. */
  872. protected function configure()
  873. {
  874. parent::configure();
  875. // fallback of $this->tmp
  876. if (!$this->tmp && $this->tmbPathWritable) {
  877. $this->tmp = $this->tmbPath;
  878. }
  879. }
  880. /*********************************************************************/
  881. /* FS API */
  882. /*********************************************************************/
  883. /**
  884. * Close opened connection.
  885. *
  886. * @author Dmitry (dio) Levashov
  887. **/
  888. public function umount()
  889. {
  890. }
  891. /**
  892. * Return fileinfo based on filename
  893. * For item ID based path file system
  894. * Please override if needed on each drivers.
  895. *
  896. * @param string $path file cache
  897. *
  898. * @return array|boolean
  899. * @throws elFinderAbortException
  900. */
  901. protected function isNameExists($path)
  902. {
  903. list(, $name, $parent) = $this->_bd_splitPath($path);
  904. // We can not use it because the search of Box.com there is a time lag.
  905. // ref. https://docs.box.com/reference#searching-for-content
  906. // > Note: If an item is added to Box then it becomes accessible through the search endpoint after ten minutes.
  907. /***
  908. * $url = self::API_URL.'/search?limit=1&offset=0&content_types=name&ancestor_folder_ids='.rawurlencode($pid)
  909. * .'&query='.rawurlencode('"'.$name.'"')
  910. * .'fields='.self::FETCHFIELDS;
  911. * $raw = $this->_bd_fetch($url);
  912. * if (is_array($raw) && count($raw)) {
  913. * return $this->_bd_parseRaw($raw);
  914. * }
  915. ***/
  916. $phash = $this->encode($parent);
  917. // do not recursive search
  918. $searchExDirReg = $this->options['searchExDirReg'];
  919. $this->options['searchExDirReg'] = '/.*/';
  920. $search = $this->search($name, array(), $phash);
  921. $this->options['searchExDirReg'] = $searchExDirReg;
  922. if ($search) {
  923. $f = false;
  924. foreach($search as $f) {
  925. if ($f['name'] !== $name) {
  926. $f = false;
  927. }
  928. if ($f) {
  929. break;
  930. }
  931. }
  932. return $f;
  933. }
  934. return false;
  935. }
  936. /**
  937. * Cache dir contents.
  938. *
  939. * @param string $path dir path
  940. *
  941. * @return
  942. * @throws Exception
  943. * @author Dmitry Levashov
  944. */
  945. protected function cacheDir($path)
  946. {
  947. $this->dirsCache[$path] = array();
  948. $hasDir = false;
  949. if ($path == '/') {
  950. $items = $this->_bd_query('0', $fetch_self = true); // get root directory with folder & files
  951. $itemId = $items->id;
  952. } else {
  953. list(, $itemId) = $this->_bd_splitPath($path);
  954. }
  955. $res = $this->_bd_query($itemId);
  956. if ($res) {
  957. foreach ($res as $raw) {
  958. if ($stat = $this->_bd_parseRaw($raw)) {
  959. $itemPath = $this->_joinPath($path, $raw->id);
  960. $stat = $this->updateCache($itemPath, $stat);
  961. if (empty($stat['hidden'])) {
  962. if (!$hasDir && $stat['mime'] === 'directory') {
  963. $hasDir = true;
  964. }
  965. $this->dirsCache[$path][] = $itemPath;
  966. }
  967. }
  968. }
  969. }
  970. if (isset($this->sessionCache['subdirs'])) {
  971. $this->sessionCache['subdirs'][$path] = $hasDir;
  972. }
  973. return $this->dirsCache[$path];
  974. }
  975. /**
  976. * Copy file/recursive copy dir only in current volume.
  977. * Return new file path or false.
  978. *
  979. * @param string $src source path
  980. * @param string $dst destination dir path
  981. * @param string $name new file name (optionaly)
  982. *
  983. * @return string|false
  984. * @author Dmitry (dio) Levashov
  985. * @author Naoki Sawada
  986. **/
  987. protected function copy($src, $dst, $name)
  988. {
  989. if ($res = $this->_copy($src, $dst, $name)) {
  990. $this->added[] = $this->stat($res);
  991. return $res;
  992. } else {
  993. return $this->setError(elFinder::ERROR_COPY, $this->_path($src));
  994. }
  995. }
  996. /**
  997. * Remove file/ recursive remove dir.
  998. *
  999. * @param string $path file path
  1000. * @param bool $force try to remove even if file locked
  1001. *
  1002. * @return bool
  1003. * @throws elFinderAbortException
  1004. * @author Dmitry (dio) Levashov
  1005. * @author Naoki Sawada
  1006. */
  1007. protected function remove($path, $force = false)
  1008. {
  1009. $stat = $this->stat($path);
  1010. $stat['realpath'] = $path;
  1011. $this->rmTmb($stat);
  1012. $this->clearcache();
  1013. if (empty($stat)) {
  1014. return $this->setError(elFinder::ERROR_RM, $this->_path($path), elFinder::ERROR_FILE_NOT_FOUND);
  1015. }
  1016. if (!$force && !empty($stat['locked'])) {
  1017. return $this->setError(elFinder::ERROR_LOCKED, $this->_path($path));
  1018. }
  1019. if ($stat['mime'] == 'directory') {
  1020. if (!$this->_rmdir($path)) {
  1021. return $this->setError(elFinder::ERROR_RM, $this->_path($path));
  1022. }
  1023. } else {
  1024. if (!$this->_unlink($path)) {
  1025. return $this->setError(elFinder::ERROR_RM, $this->_path($path));
  1026. }
  1027. }
  1028. $this->removed[] = $stat;
  1029. return true;
  1030. }
  1031. /**
  1032. * Create thumnbnail and return it's URL on success.
  1033. *
  1034. * @param string $path file path
  1035. * @param $stat
  1036. *
  1037. * @return string|false
  1038. * @throws ImagickException
  1039. * @throws elFinderAbortException
  1040. * @author Dmitry (dio) Levashov
  1041. * @author Naoki Sawada
  1042. */
  1043. protected function createTmb($path, $stat)
  1044. {
  1045. if (!$stat || !$this->canCreateTmb($path, $stat)) {
  1046. return false;
  1047. }
  1048. $name = $this->tmbname($stat);
  1049. $tmb = $this->tmbPath . DIRECTORY_SEPARATOR . $name;
  1050. // copy image into tmbPath so some drivers does not store files on local fs
  1051. if (!$data = $this->_bd_getThumbnail($path)) {
  1052. // try get full contents as fallback
  1053. if (!$data = $this->_getContents($path)) {
  1054. return false;
  1055. }
  1056. }
  1057. if (!file_put_contents($tmb, $data)) {
  1058. return false;
  1059. }
  1060. $tmbSize = $this->tmbSize;
  1061. if (($s = getimagesize($tmb)) == false) {
  1062. return false;
  1063. }
  1064. $result = true;
  1065. /* If image smaller or equal thumbnail size - just fitting to thumbnail square */
  1066. if ($s[0] <= $tmbSize && $s[1] <= $tmbSize) {
  1067. $result = $this->imgSquareFit($tmb, $tmbSize, $tmbSize, 'center', 'middle', $this->options['tmbBgColor'], 'png');
  1068. } else {
  1069. if ($this->options['tmbCrop']) {
  1070. /* Resize and crop if image bigger than thumbnail */
  1071. if (!(($s[0] > $tmbSize && $s[1] <= $tmbSize) || ($s[0] <= $tmbSize && $s[1] > $tmbSize)) || ($s[0] > $tmbSize && $s[1] > $tmbSize)) {
  1072. $result = $this->imgResize($tmb, $tmbSize, $tmbSize, true, false, 'png');
  1073. }
  1074. if ($result && ($s = getimagesize($tmb)) != false) {
  1075. $x = $s[0] > $tmbSize ? intval(($s[0] - $tmbSize) / 2) : 0;
  1076. $y = $s[1] > $tmbSize ? intval(($s[1] - $tmbSize) / 2) : 0;
  1077. $result = $this->imgCrop($tmb, $tmbSize, $tmbSize, $x, $y, 'png');
  1078. }
  1079. } else {
  1080. $result = $this->imgResize($tmb, $tmbSize, $tmbSize, true, true, 'png');
  1081. }
  1082. if ($result) {
  1083. $result = $this->imgSquareFit($tmb, $tmbSize, $tmbSize, 'center', 'middle', $this->options['tmbBgColor'], 'png');
  1084. }
  1085. }
  1086. if (!$result) {
  1087. unlink($tmb);
  1088. return false;
  1089. }
  1090. return $name;
  1091. }
  1092. /**
  1093. * Return thumbnail file name for required file.
  1094. *
  1095. * @param array $stat file stat
  1096. *
  1097. * @return string
  1098. * @author Dmitry (dio) Levashov
  1099. **/
  1100. protected function tmbname($stat)
  1101. {
  1102. return $this->tmbPrefix . $stat['rev'] . $stat['ts'] . '.png';
  1103. }
  1104. /**
  1105. * Return content URL.
  1106. *
  1107. * @param object $raw data
  1108. *
  1109. * @return string
  1110. * @author Naoki Sawada
  1111. **/
  1112. protected function getSharedWebContentLink($raw)
  1113. {
  1114. if ($raw->shared_link->url) {
  1115. return sprintf('https://app.box.com/index.php?rm=box_download_shared_file&shared_name=%s&file_id=f_%s', basename($raw->shared_link->url), $raw->id);
  1116. } elseif ($raw->shared_link->download_url) {
  1117. return $raw->shared_link->download_url;
  1118. }
  1119. return false;
  1120. }
  1121. /**
  1122. * Return content URL.
  1123. *
  1124. * @param string $hash file hash
  1125. * @param array $options options
  1126. *
  1127. * @return string
  1128. * @throws Exception
  1129. * @author Naoki Sawada
  1130. */
  1131. public function getContentUrl($hash, $options = array())
  1132. {
  1133. if (!empty($options['onetime']) && $this->options['onetimeUrl']) {
  1134. return parent::getContentUrl($hash, $options);
  1135. }
  1136. if (!empty($options['temporary'])) {
  1137. // try make temporary file
  1138. $url = parent::getContentUrl($hash, $options);
  1139. if ($url) {
  1140. return $url;
  1141. }
  1142. }
  1143. if (($file = $this->file($hash)) == false || !$file['url'] || $file['url'] == 1) {
  1144. $path = $this->decode($hash);
  1145. list(, $itemId) = $this->_bd_splitPath($path);
  1146. $params['shared_link']['access'] = 'open'; //open|company|collaborators
  1147. $url = self::API_URL . '/files/' . $itemId;
  1148. $curl = $this->_bd_prepareCurl(array(
  1149. CURLOPT_URL => $url,
  1150. CURLOPT_CUSTOMREQUEST => 'PUT',
  1151. CURLOPT_POSTFIELDS => json_encode($params),
  1152. ));
  1153. $res = $this->_bd_curlExec($curl, true, array(
  1154. // The data is sent as JSON as per Box documentation.
  1155. 'Content-Type: application/json',
  1156. ));
  1157. if ($url = $this->getSharedWebContentLink($res)) {
  1158. return $url;
  1159. }
  1160. }
  1161. return '';
  1162. }
  1163. /*********************** paths/urls *************************/
  1164. /**
  1165. * Return parent directory path.
  1166. *
  1167. * @param string $path file path
  1168. *
  1169. * @return string
  1170. * @author Dmitry (dio) Levashov
  1171. **/
  1172. protected function _dirname($path)
  1173. {
  1174. list(, , $dirname) = $this->_bd_splitPath($path);
  1175. return $dirname;
  1176. }
  1177. /**
  1178. * Return file name.
  1179. *
  1180. * @param string $path file path
  1181. *
  1182. * @return string
  1183. * @author Dmitry (dio) Levashov
  1184. **/
  1185. protected function _basename($path)
  1186. {
  1187. list(, $basename) = $this->_bd_splitPath($path);
  1188. return $basename;
  1189. }
  1190. /**
  1191. * Join dir name and file name and retur full path.
  1192. *
  1193. * @param string $dir
  1194. * @param string $name
  1195. *
  1196. * @return string
  1197. * @author Dmitry (dio) Levashov
  1198. **/
  1199. protected function _joinPath($dir, $name)
  1200. {
  1201. if (strval($dir) === '0') {
  1202. $dir = '';
  1203. }
  1204. return $this->_normpath($dir . '/' . $name);
  1205. }
  1206. /**
  1207. * Return normalized path, this works the same as os.path.normpath() in Python.
  1208. *
  1209. * @param string $path path
  1210. *
  1211. * @return string
  1212. * @author Troex Nevelin
  1213. **/
  1214. protected function _normpath($path)
  1215. {
  1216. if (DIRECTORY_SEPARATOR !== '/') {
  1217. $path = str_replace(DIRECTORY_SEPARATOR, '/', $path);
  1218. }
  1219. $path = '/' . ltrim($path, '/');
  1220. return $path;
  1221. }
  1222. /**
  1223. * Return file path related to root dir.
  1224. *
  1225. * @param string $path file path
  1226. *
  1227. * @return string
  1228. * @author Dmitry (dio) Levashov
  1229. **/
  1230. protected function _relpath($path)
  1231. {
  1232. return $path;
  1233. }
  1234. /**
  1235. * Convert path related to root dir into real path.
  1236. *
  1237. * @param string $path file path
  1238. *
  1239. * @return string
  1240. * @author Dmitry (dio) Levashov
  1241. **/
  1242. protected function _abspath($path)
  1243. {
  1244. return $path;
  1245. }
  1246. /**
  1247. * Return fake path started from root dir.
  1248. *
  1249. * @param string $path file path
  1250. *
  1251. * @return string
  1252. * @author Dmitry (dio) Levashov
  1253. **/
  1254. protected function _path($path)
  1255. {
  1256. return $this->rootName . $this->_normpath(substr($path, strlen($this->root)));
  1257. }
  1258. /**
  1259. * Return true if $path is children of $parent.
  1260. *
  1261. * @param string $path path to check
  1262. * @param string $parent parent path
  1263. *
  1264. * @return bool
  1265. * @author Dmitry (dio) Levashov
  1266. **/
  1267. protected function _inpath($path, $parent)
  1268. {
  1269. return $path == $parent || strpos($path, $parent . '/') === 0;
  1270. }
  1271. /***************** file stat ********************/
  1272. /**
  1273. * Return stat for given path.
  1274. * Stat contains following fields:
  1275. * - (int) size file size in b. required
  1276. * - (int) ts file modification time in unix time. required
  1277. * - (string) mime mimetype. required for folders, others - optionally
  1278. * - (bool) read read permissions. required
  1279. * - (bool) write write permissions. required
  1280. * - (bool) locked is object locked. optionally
  1281. * - (bool) hidden is object hidden. optionally
  1282. * - (string) alias for symlinks - link target path relative to root path. optionally
  1283. * - (string) target for symlinks - link target path. optionally.
  1284. * If file does not exists - returns empty array or false.
  1285. *
  1286. * @param string $path file path
  1287. *
  1288. * @return array|false
  1289. * @throws Exception
  1290. * @author Dmitry (dio) Levashov
  1291. */
  1292. protected function _stat($path)
  1293. {
  1294. if ($raw = $this->_bd_getRawItem($path)) {
  1295. return $this->_bd_parseRaw($raw);
  1296. }
  1297. return false;
  1298. }
  1299. /**
  1300. * Return true if path is dir and has at least one childs directory.
  1301. *
  1302. * @param string $path dir path
  1303. *
  1304. * @return bool
  1305. * @throws Exception
  1306. * @author Dmitry (dio) Levashov
  1307. */
  1308. protected function _subdirs($path)
  1309. {
  1310. list(, $itemId) = $this->_bd_splitPath($path);
  1311. $path = '/folders/' . $itemId . '/items?limit=1&offset=0&fields=' . self::FETCHFIELDS;
  1312. $url = self::API_URL . $path;
  1313. if ($res = $this->_bd_fetch($url)) {
  1314. if ($res[0]->type == 'folder') {
  1315. return true;
  1316. }
  1317. }
  1318. return false;
  1319. }
  1320. /**
  1321. * Return object width and height
  1322. * Ususaly used for images, but can be realize for video etc...
  1323. *
  1324. * @param string $path file path
  1325. * @param string $mime file mime type
  1326. *
  1327. * @return string
  1328. * @throws ImagickException
  1329. * @throws elFinderAbortException
  1330. * @author Dmitry (dio) Levashov
  1331. */
  1332. protected function _dimensions($path, $mime)
  1333. {
  1334. if (strpos($mime, 'image') !== 0) {
  1335. return '';
  1336. }
  1337. $ret = '';
  1338. if ($work = $this->getWorkFile($path)) {
  1339. if ($size = @getimagesize($work)) {
  1340. $cache['width'] = $size[0];
  1341. $cache['height'] = $size[1];
  1342. $ret = array('dim' => $size[0] . 'x' . $size[1]);
  1343. $srcfp = fopen($work, 'rb');
  1344. $target = isset(elFinder::$currentArgs['target'])? elFinder::$currentArgs['target'] : '';
  1345. if ($subImgLink = $this->getSubstituteImgLink($target, $size, $srcfp)) {
  1346. $ret['url'] = $subImgLink;
  1347. }
  1348. }
  1349. }
  1350. is_file($work) && @unlink($work);
  1351. return $ret;
  1352. }
  1353. /******************** file/dir content *********************/
  1354. /**
  1355. * Return files list in directory.
  1356. *
  1357. * @param string $path dir path
  1358. *
  1359. * @return array
  1360. * @throws Exception
  1361. * @author Dmitry (dio) Levashov
  1362. * @author Cem (DiscoFever)
  1363. */
  1364. protected function _scandir($path)
  1365. {
  1366. return isset($this->dirsCache[$path])
  1367. ? $this->dirsCache[$path]
  1368. : $this->cacheDir($path);
  1369. }
  1370. /**
  1371. * Open file and return file pointer.
  1372. *
  1373. * @param string $path file path
  1374. * @param string $mode
  1375. *
  1376. * @return resource|false
  1377. * @author Dmitry (dio) Levashov
  1378. */
  1379. protected function _fopen($path, $mode = 'rb')
  1380. {
  1381. if ($mode === 'rb' || $mode === 'r') {
  1382. list(, $itemId) = $this->_bd_splitPath($path);
  1383. $data = array(
  1384. 'target' => self::API_URL . '/files/' . $itemId . '/content',
  1385. 'headers' => array('Authorization: Bearer ' . $this->token->data->access_token),
  1386. );
  1387. // to support range request
  1388. if (func_num_args() > 2) {
  1389. $opts = func_get_arg(2);
  1390. } else {
  1391. $opts = array();
  1392. }
  1393. if (!empty($opts['httpheaders'])) {
  1394. $data['headers'] = array_merge($opts['httpheaders'], $data['headers']);
  1395. }
  1396. return elFinder::getStreamByUrl($data);
  1397. }
  1398. return false;
  1399. }
  1400. /**
  1401. * Close opened file.
  1402. *
  1403. * @param resource $fp file pointer
  1404. * @param string $path
  1405. *
  1406. * @return void
  1407. * @author Dmitry (dio) Levashov
  1408. */
  1409. protected function _fclose($fp, $path = '')
  1410. {
  1411. is_resource($fp) && fclose($fp);
  1412. if ($path) {
  1413. unlink($this->getTempFile($path));
  1414. }
  1415. }
  1416. /******************** file/dir manipulations *************************/
  1417. /**
  1418. * Create dir and return created dir path or false on failed.
  1419. *
  1420. * @param string $path parent dir path
  1421. * @param string $name new directory name
  1422. *
  1423. * @return string|bool
  1424. * @author Dmitry (dio) Levashov
  1425. **/
  1426. protected function _mkdir($path, $name)
  1427. {
  1428. try {
  1429. list(, $parentId) = $this->_bd_splitPath($path);
  1430. $params = array('name' => $name, 'parent' => array('id' => $parentId));
  1431. $url = self::API_URL . '/folders';
  1432. $curl = $this->_bd_prepareCurl(array(
  1433. CURLOPT_URL => $url,
  1434. CURLOPT_POST => true,
  1435. CURLOPT_POSTFIELDS => json_encode($params),
  1436. ));
  1437. //create the Folder in the Parent
  1438. $folder = $this->_bd_curlExec($curl, $path);
  1439. return $this->_joinPath($path, $folder->id);
  1440. } catch (Exception $e) {
  1441. return $this->setError('Box error: ' . $e->getMessage());
  1442. }
  1443. }
  1444. /**
  1445. * Create file and return it's path or false on failed.
  1446. *
  1447. * @param string $path parent dir path
  1448. * @param string $name new file name
  1449. *
  1450. * @return string|bool
  1451. * @author Dmitry (dio) Levashov
  1452. **/
  1453. protected function _mkfile($path, $name)
  1454. {
  1455. return $this->_save($this->tmpfile(), $path, $name, array());
  1456. }
  1457. /**
  1458. * Create symlink. FTP driver does not support symlinks.
  1459. *
  1460. * @param string $target link target
  1461. * @param string $path symlink path
  1462. *
  1463. * @return bool
  1464. * @author Dmitry (dio) Levashov
  1465. **/
  1466. protected function _symlink($target, $path, $name)
  1467. {
  1468. return false;
  1469. }
  1470. /**
  1471. * Copy file into another file.
  1472. *
  1473. * @param string $source source file path
  1474. * @param string $targetDir target directory path
  1475. * @param string $name new file name
  1476. *
  1477. * @return string|false
  1478. * @author Dmitry (dio) Levashov
  1479. **/
  1480. protected function _copy($source, $targetDir, $name)
  1481. {
  1482. try {
  1483. //Set the Parent id
  1484. list(, $parentId) = $this->_bd_splitPath($targetDir);
  1485. list(, $srcId) = $this->_bd_splitPath($source);
  1486. $srcItem = $this->_bd_getRawItem($source);
  1487. $properties = array('name' => $name, 'parent' => array('id' => $parentId));
  1488. $data = (object)$properties;
  1489. $type = ($srcItem->type === 'folder') ? 'folders' : 'files';
  1490. $url = self::API_URL . '/' . $type . '/' . $srcId . '/copy';
  1491. $curl = $this->_bd_prepareCurl(array(
  1492. CURLOPT_URL => $url,
  1493. CURLOPT_POST => true,
  1494. CURLOPT_POSTFIELDS => json_encode($data),
  1495. ));
  1496. //copy File in the Parent
  1497. $result = $this->_bd_curlExec($curl, $targetDir);
  1498. if (isset($result->id)) {
  1499. if ($type === 'folders' && isset($this->sessionCache['subdirs'])) {
  1500. $this->sessionCache['subdirs'][$targetDir] = true;
  1501. }
  1502. return $this->_joinPath($targetDir, $result->id);
  1503. }
  1504. return false;
  1505. } catch (Exception $e) {
  1506. return $this->setError('Box error: ' . $e->getMessage());
  1507. }
  1508. }
  1509. /**
  1510. * Move file into another parent dir.
  1511. * Return new file path or false.
  1512. *
  1513. * @param string $source source file path
  1514. * @param string $target target dir path
  1515. * @param string $name file name
  1516. *
  1517. * @return string|bool
  1518. * @author Dmitry (dio) Levashov
  1519. **/
  1520. protected function _move($source, $targetDir, $name)
  1521. {
  1522. try {
  1523. //moving and renaming a file or directory
  1524. //Set new Parent and remove old parent
  1525. list(, $parentId) = $this->_bd_splitPath($targetDir);
  1526. list(, $itemId) = $this->_bd_splitPath($source);
  1527. $srcItem = $this->_bd_getRawItem($source);
  1528. //rename or move file or folder in destination target
  1529. $properties = array('name' => $name, 'parent' => array('id' => $parentId));
  1530. $type = ($srcItem->type === 'folder') ? 'folders' : 'files';
  1531. $url = self::API_URL . '/' . $type . '/' . $itemId;
  1532. $data = (object)$properties;
  1533. $curl = $this->_bd_prepareCurl(array(
  1534. CURLOPT_URL => $url,
  1535. CURLOPT_CUSTOMREQUEST => 'PUT',
  1536. CURLOPT_POSTFIELDS => json_encode($data),
  1537. ));
  1538. $result = $this->_bd_curlExec($curl, $targetDir, array(
  1539. // The data is sent as JSON as per Box documentation.
  1540. 'Content-Type: application/json',
  1541. ));
  1542. if ($result && isset($result->id)) {
  1543. return $this->_joinPath($targetDir, $result->id);
  1544. }
  1545. return false;
  1546. } catch (Exception $e) {
  1547. return $this->setError('Box error: ' . $e->getMessage());
  1548. }
  1549. }
  1550. /**
  1551. * Remove file.
  1552. *
  1553. * @param string $path file path
  1554. *
  1555. * @return bool
  1556. * @author Dmitry (dio) Levashov
  1557. **/
  1558. protected function _unlink($path)
  1559. {
  1560. return $this->_bd_unlink($path, 'files');
  1561. }
  1562. /**
  1563. * Remove dir.
  1564. *
  1565. * @param string $path dir path
  1566. *
  1567. * @return bool
  1568. * @author Dmitry (dio) Levashov
  1569. **/
  1570. protected function _rmdir($path)
  1571. {
  1572. return $this->_bd_unlink($path, 'folders');
  1573. }
  1574. /**
  1575. * Create new file and write into it from file pointer.
  1576. * Return new file path or false on error.
  1577. *
  1578. * @param resource $fp file pointer
  1579. * @param string $dir target dir path
  1580. * @param string $name file name
  1581. * @param array $stat file stat (required by some virtual fs)
  1582. *
  1583. * @return bool|string
  1584. * @author Dmitry (dio) Levashov
  1585. **/
  1586. protected function _save($fp, $path, $name, $stat)
  1587. {
  1588. $itemId = '';
  1589. if ($name === '') {
  1590. list($parentId, $itemId, $parent) = $this->_bd_splitPath($path);
  1591. } else {
  1592. if ($stat) {
  1593. if (isset($stat['name'])) {
  1594. $name = $stat['name'];
  1595. }
  1596. if (isset($stat['rev']) && strpos($stat['hash'], $this->id) === 0) {
  1597. $itemId = $stat['rev'];
  1598. }
  1599. }
  1600. list(, $parentId) = $this->_bd_splitPath($path);
  1601. $parent = $path;
  1602. }
  1603. try {
  1604. //Create or Update a file
  1605. $metaDatas = stream_get_meta_data($fp);
  1606. $tmpFilePath = isset($metaDatas['uri']) ? $metaDatas['uri'] : '';
  1607. // remote contents
  1608. if (!$tmpFilePath || empty($metaDatas['seekable'])) {
  1609. $tmpHandle = $this->tmpfile();
  1610. stream_copy_to_stream($fp, $tmpHandle);
  1611. $metaDatas = stream_get_meta_data($tmpHandle);
  1612. $tmpFilePath = $metaDatas['uri'];
  1613. }
  1614. if ($itemId === '') {
  1615. //upload or create new file in destination target
  1616. $properties = array('name' => $name, 'parent' => array('id' => $parentId));
  1617. $url = self::UPLOAD_URL . '/files/content';
  1618. } else {
  1619. //update existing file in destination target
  1620. $properties = array('name' => $name);
  1621. $url = self::UPLOAD_URL . '/files/' . $itemId . '/content';
  1622. }
  1623. if (class_exists('CURLFile')) {
  1624. $cfile = new CURLFile($tmpFilePath);
  1625. } else {
  1626. $cfile = '@' . $tmpFilePath;
  1627. }
  1628. $params = array('attributes' => json_encode($properties), 'file' => $cfile);
  1629. $curl = $this->_bd_prepareCurl(array(
  1630. CURLOPT_URL => $url,
  1631. CURLOPT_POST => true,
  1632. CURLOPT_POSTFIELDS => $params,
  1633. ));
  1634. $file = $this->_bd_curlExec($curl, $parent);
  1635. return $this->_joinPath($parent, $file->entries[0]->id);
  1636. } catch (Exception $e) {
  1637. return $this->setError('Box error: ' . $e->getMessage());
  1638. }
  1639. }
  1640. /**
  1641. * Get file contents.
  1642. *
  1643. * @param string $path file path
  1644. *
  1645. * @return string|false
  1646. * @author Dmitry (dio) Levashov
  1647. **/
  1648. protected function _getContents($path)
  1649. {
  1650. try {
  1651. list(, $itemId) = $this->_bd_splitPath($path);
  1652. $url = self::API_URL . '/files/' . $itemId . '/content';
  1653. $contents = $this->_bd_fetch($url, true);
  1654. } catch (Exception $e) {
  1655. return $this->setError('Box error: ' . $e->getMessage());
  1656. }
  1657. return $contents;
  1658. }
  1659. /**
  1660. * Write a string to a file.
  1661. *
  1662. * @param string $path file path
  1663. * @param string $content new file content
  1664. *
  1665. * @return bool
  1666. * @author Dmitry (dio) Levashov
  1667. **/
  1668. protected function _filePutContents($path, $content)
  1669. {
  1670. $res = false;
  1671. if ($local = $this->getTempFile($path)) {
  1672. if (file_put_contents($local, $content, LOCK_EX) !== false
  1673. && ($fp = fopen($local, 'rb'))) {
  1674. clearstatcache();
  1675. $res = $this->_save($fp, $path, '', array());
  1676. fclose($fp);
  1677. }
  1678. file_exists($local) && unlink($local);
  1679. }
  1680. return $res;
  1681. }
  1682. /**
  1683. * Detect available archivers.
  1684. **/
  1685. protected function _checkArchivers()
  1686. {
  1687. // die('Not yet implemented. (_checkArchivers)');
  1688. return array();
  1689. }
  1690. /**
  1691. * chmod implementation.
  1692. *
  1693. * @return bool
  1694. **/
  1695. protected function _chmod($path, $mode)
  1696. {
  1697. return false;
  1698. }
  1699. /**
  1700. * Extract files from archive.
  1701. *
  1702. * @param string $path archive path
  1703. * @param array $arc archiver command and arguments (same as in $this->archivers)
  1704. *
  1705. * @return true
  1706. * @author Dmitry (dio) Levashov,
  1707. * @author Alexey Sukhotin
  1708. **/
  1709. protected function _extract($path, $arc)
  1710. {
  1711. die('Not yet implemented. (_extract)');
  1712. }
  1713. /**
  1714. * Create archive and return its path.
  1715. *
  1716. * @param string $dir target dir
  1717. * @param array $files files names list
  1718. * @param string $name archive name
  1719. * @param array $arc archiver options
  1720. *
  1721. * @return string|bool
  1722. * @author Dmitry (dio) Levashov,
  1723. * @author Alexey Sukhotin
  1724. **/
  1725. protected function _archive($dir, $files, $name, $arc)
  1726. {
  1727. die('Not yet implemented. (_archive)');
  1728. }
  1729. } // END class