elFinderVolumeBox.class.php 54 KB

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