elFinderVolumeBox.class.php 54 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857
  1. <?php
  2. elFinder::$netDrivers['box'] = 'Box';
  3. /**
  4. * Simple elFinder driver for BoxDrive
  5. * Box.com API v2.0.
  6. *
  7. * @author Dmitry (dio) Levashov
  8. * @author Cem (discofever)
  9. **/
  10. class elFinderVolumeBox extends elFinderVolumeDriver
  11. {
  12. /**
  13. * Driver id
  14. * Must be started from letter and contains [a-z0-9]
  15. * Used as part of volume id.
  16. *
  17. * @var string
  18. **/
  19. protected $driverId = 'bd';
  20. /**
  21. * @var string The base URL for API requests
  22. */
  23. const API_URL = 'https://api.box.com/2.0';
  24. /**
  25. * @var string The base URL for authorization requests
  26. */
  27. const AUTH_URL = 'https://www.box.com/api/oauth2/authorize';
  28. /**
  29. * @var string The base URL for token requests
  30. */
  31. const TOKEN_URL = 'https://www.box.com/api/oauth2/token';
  32. /**
  33. * @var string The base URL for upload requests
  34. */
  35. const UPLOAD_URL = 'https://upload.box.com/api/2.0';
  36. /**
  37. * Fetch fields list.
  38. *
  39. * @var string
  40. */
  41. const FETCHFIELDS = 'type,id,name,created_at,modified_at,description,size,parent,permissions,file_version,shared_link';
  42. /**
  43. * Box.com token object.
  44. *
  45. * @var object
  46. **/
  47. protected $token = null;
  48. /**
  49. * Directory for tmp files
  50. * If not set driver will try to use tmbDir as tmpDir.
  51. *
  52. * @var string
  53. **/
  54. protected $tmp = '';
  55. /**
  56. * Net mount key.
  57. *
  58. * @var string
  59. **/
  60. public $netMountKey = '';
  61. /**
  62. * Thumbnail prefix.
  63. *
  64. * @var string
  65. **/
  66. private $tmbPrefix = '';
  67. /**
  68. * hasCache by folders.
  69. *
  70. * @var array
  71. **/
  72. protected $HasdirsCache = array();
  73. /**
  74. * Constructor
  75. * Extend options with required fields.
  76. *
  77. * @author Dmitry (dio) Levashov
  78. * @author Cem (DiscoFever)
  79. **/
  80. public function __construct()
  81. {
  82. $opts = array(
  83. 'client_id' => '',
  84. 'client_secret' => '',
  85. 'accessToken' => '',
  86. 'root' => 'Box.com',
  87. 'path' => '/',
  88. 'separator' => '/',
  89. 'tmbPath' => '',
  90. 'tmbURL' => '',
  91. 'tmpPath' => '',
  92. 'acceptedName' => '#^[^/\\?*:|"<>]*[^./\\?*:|"<>]$#',
  93. 'rootCssClass' => 'elfinder-navbar-root-box',
  94. );
  95. $this->options = array_merge($this->options, $opts);
  96. $this->options['mimeDetect'] = 'internal';
  97. }
  98. /*********************************************************************/
  99. /* ORIGINAL FUNCTIONS */
  100. /*********************************************************************/
  101. /**
  102. * Get Parent ID, Item ID, Parent Path as an array from path.
  103. *
  104. * @param string $path
  105. *
  106. * @return array
  107. */
  108. protected function _bd_splitPath($path)
  109. {
  110. $path = trim($path, '/');
  111. $pid = '';
  112. if ($path === '') {
  113. $id = '0';
  114. $parent = '';
  115. } else {
  116. $paths = explode('/', trim($path, '/'));
  117. $id = array_pop($paths);
  118. if ($paths) {
  119. $parent = '/'.implode('/', $paths);
  120. $pid = array_pop($paths);
  121. } else {
  122. $pid = '0';
  123. $parent = '/';
  124. }
  125. }
  126. return array($pid, $id, $parent);
  127. }
  128. /**
  129. * Obtains a new access token from OAuth. This token is valid for one hour.
  130. *
  131. * @param string $clientSecret The Box client secret
  132. * @param string $code The code returned by Box after
  133. * successful log in
  134. * @param string $redirectUri Must be the same as the redirect URI passed
  135. * to LoginUrl
  136. *
  137. * @throws \Exception Thrown if this Client instance's clientId is not set
  138. * @throws \Exception Thrown if the redirect URI of this Client instance's
  139. * state is not set
  140. */
  141. protected function _bd_obtainAccessToken($client_id, $client_secret, $code)
  142. {
  143. if (null === $client_id) {
  144. return $this->setError('The client ID must be set to call obtainAccessToken()');
  145. }
  146. if (null === $client_secret) {
  147. return $this->setError('The client Secret must be set to call obtainAccessToken()');
  148. }
  149. if (null === $code) {
  150. return $this->setError('Authorization code must be set to call obtainAccessToken()');
  151. }
  152. $url = self::TOKEN_URL;
  153. $curl = curl_init();
  154. $fields = http_build_query(
  155. array(
  156. 'client_id' => $client_id,
  157. 'client_secret' => $client_secret,
  158. 'code' => $code,
  159. 'grant_type' => 'authorization_code',
  160. )
  161. );
  162. curl_setopt_array($curl, array(
  163. // General options.
  164. CURLOPT_RETURNTRANSFER => true,
  165. CURLOPT_POST => true,
  166. CURLOPT_POSTFIELDS => $fields,
  167. CURLOPT_URL => $url,
  168. ));
  169. $decoded = $this->_bd_curlExec($curl, true, array('Content-Length: '.strlen($fields)));
  170. return (object) array(
  171. 'expires' => time() + $decoded->expires_in - 30,
  172. 'data' => $decoded,
  173. );
  174. }
  175. /**
  176. * Get token and auto refresh.
  177. *
  178. * @return true|string error message
  179. */
  180. protected function _bd_refreshToken()
  181. {
  182. if (!property_exists($this->token, 'expires') || $this->token->expires < time()) {
  183. if (!$token = $this->session->get('BoxTokens')) {
  184. $token = $this->token;
  185. }
  186. if (empty($token->data->refresh_token)) {
  187. $this->session->remove('BoxTokens');
  188. throw new \Exception(elFinder::ERROR_REAUTH_REQUIRE);
  189. }
  190. if (!$this->options['client_id']) {
  191. $this->options['client_id'] = ELFINDER_BOX_CLIENTID;
  192. }
  193. if (!$this->options['client_secret']) {
  194. $this->options['client_secret'] = ELFINDER_BOX_CLIENTSECRET;
  195. }
  196. $url = self::TOKEN_URL;
  197. $curl = curl_init();
  198. curl_setopt_array($curl, array(
  199. // General options.
  200. CURLOPT_RETURNTRANSFER => true,
  201. CURLOPT_POST => true, // i am sending post data
  202. CURLOPT_POSTFIELDS => 'client_id='.urlencode($this->options['client_id'])
  203. .'&client_secret='.urlencode($this->options['client_secret'])
  204. .'&grant_type=refresh_token'
  205. .'&refresh_token='.urlencode($token->data->refresh_token),
  206. CURLOPT_URL => $url,
  207. ));
  208. $decoded = $this->_bd_curlExec($curl);
  209. if (empty($decoded->access_token)) {
  210. throw new \Exception(elFinder::ERROR_REAUTH_REQUIRE);
  211. }
  212. $token = (object) array(
  213. 'expires' => time() + $decoded->expires_in - 30,
  214. 'data' => $decoded,
  215. );
  216. $this->session->set('BoxTokens', $token);
  217. $this->options['accessToken'] = json_encode($token);
  218. $this->token = $token;
  219. if (!empty($this->options['netkey'])) {
  220. elFinder::$instance->updateNetVolumeOption($this->options['netkey'], 'accessToken', $this->options['accessToken']);
  221. }
  222. }
  223. return true;
  224. }
  225. /**
  226. * Creates a base cURL object which is compatible with the Box.com API.
  227. *
  228. * @param array $options cURL options
  229. *
  230. * @return resource A compatible cURL object
  231. */
  232. protected function _bd_prepareCurl($options = array())
  233. {
  234. $curl = curl_init();
  235. $defaultOptions = array(
  236. // General options.
  237. CURLOPT_RETURNTRANSFER => true,
  238. );
  239. curl_setopt_array($curl, $options + $defaultOptions);
  240. return $curl;
  241. }
  242. /**
  243. * Creates a base cURL object which is compatible with the Box.com API.
  244. *
  245. * @param string $path The path of the API call (eg. /folders/0)
  246. *
  247. * @return resource A compatible cURL object
  248. */
  249. protected function _bd_fetch($url, $contents = false)
  250. {
  251. $curl = curl_init($url);
  252. curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
  253. if ($contents) {
  254. return $this->_bd_curlExec($curl, false);
  255. } else {
  256. $result = $this->_bd_curlExec($curl);
  257. if (isset($result->entries)) {
  258. $res = $result->entries;
  259. $cnt = count($res);
  260. $total = $result->total_count;
  261. $offset = $result->offset;
  262. $single = ($result->limit == 1) ? true : false;
  263. if (!$single && $total > ($offset + $cnt)) {
  264. $offset = $offset + $cnt;
  265. if (strpos($url, 'offset=') === false) {
  266. $url .= '&offset='.$offset;
  267. } else {
  268. $url = preg_replace('/^(.+?offset=)\d+(.*)$/', '${1}'.$offset.'$2', $url);
  269. }
  270. $more = $this->_bd_fetch($url);
  271. if (is_array($more)) {
  272. $res = array_merge($res, $more);
  273. }
  274. }
  275. return $res;
  276. } else {
  277. if (isset($result->type) && $result->type === 'error') {
  278. return false;
  279. } else {
  280. return $result;
  281. }
  282. }
  283. }
  284. }
  285. /**
  286. * Call curl_exec().
  287. *
  288. * @param resource $curl
  289. * @param bool|string $decodeOrParent
  290. * @param array $headers
  291. *
  292. * @throws \Exception
  293. *
  294. * @return mixed
  295. */
  296. protected function _bd_curlExec($curl, $decodeOrParent = true, $headers = array())
  297. {
  298. $headers = array_merge(array(
  299. 'Authorization: Bearer '.$this->token->data->access_token,
  300. ), $headers);
  301. $result = elFinder::curlExec($curl, array(), $headers);
  302. if (!$decodeOrParent) {
  303. return $result;
  304. }
  305. $decoded = json_decode($result);
  306. if (!empty($decoded->error_code)) {
  307. $errmsg = $decoded->error_code;
  308. if (!empty($decoded->message)) {
  309. $errmsg .= ': '.$decoded->message;
  310. }
  311. throw new \Exception($errmsg);
  312. }
  313. // make catch
  314. if ($decodeOrParent && $decodeOrParent !== true) {
  315. $raws = null;
  316. list(, $parentId) = $this->_bd_splitPath($decodeOrParent);
  317. if (isset($decoded->entries)) {
  318. $raws = $decoded->entries;
  319. } elseif (isset($decoded->id)) {
  320. $raws = array($decoded);
  321. }
  322. if ($raws) {
  323. foreach ($raws as $raw) {
  324. if (isset($raw->id)) {
  325. $stat = $this->_bd_parseRaw($raw);
  326. $itemPath = $this->_joinPath($decodeOrParent, $raw->id);
  327. $this->updateCache($itemPath, $stat);
  328. }
  329. }
  330. }
  331. }
  332. return $decoded;
  333. }
  334. /**
  335. * Drive query and fetchAll.
  336. *
  337. * @param string $sql
  338. *
  339. * @return bool|array
  340. */
  341. protected function _bd_query($itemId, $fetch_self = false, $recursive = false)
  342. {
  343. $result = [];
  344. if (null === $itemId) {
  345. $itemId = '0';
  346. }
  347. if ($fetch_self) {
  348. $path = '/folders/'.$itemId.'?fields='.self::FETCHFIELDS;
  349. } else {
  350. $path = '/folders/'.$itemId.'/items?limit=1000&fields='.self::FETCHFIELDS;
  351. }
  352. $url = self::API_URL.$path;
  353. if ($recursive) {
  354. foreach ($this->_bd_fetch($url) as $file) {
  355. if ($file->type == 'folder') {
  356. $result[] = $file;
  357. $result = array_merge($result, $this->_bd_query($file->id, $fetch_self = false, $recursive = true));
  358. } elseif ($file->type == 'file') {
  359. $result[] = $file;
  360. }
  361. }
  362. } else {
  363. $result = $this->_bd_fetch($url);
  364. if ($fetch_self && !$result) {
  365. $path = '/files/'.$itemId.'?fields='.self::FETCHFIELDS;
  366. $url = self::API_URL.$path;
  367. $result = $this->_bd_fetch($url);
  368. }
  369. }
  370. return $result;
  371. }
  372. /**
  373. * Get dat(box metadata) from Box.com.
  374. *
  375. * @param string $path
  376. *
  377. * @return array box metadata
  378. */
  379. protected function _bd_getRawItem($path)
  380. {
  381. if ($path == '/') {
  382. return $this->_bd_query('0', $fetch_self = true);
  383. }
  384. list(, $itemId) = $this->_bd_splitPath($path);
  385. try {
  386. return $this->_bd_query($itemId, $fetch_self = true);
  387. } catch (Exception $e) {
  388. return array();
  389. }
  390. }
  391. /**
  392. * Parse line from box metadata output and return file stat (array).
  393. *
  394. * @param string $raw line from ftp_rawlist() output
  395. *
  396. * @return array
  397. *
  398. * @author Dmitry Levashov
  399. **/
  400. protected function _bd_parseRaw($raw)
  401. {
  402. $stat = array();
  403. $stat['rev'] = isset($raw->id) ? $raw->id : 'root';
  404. $stat['name'] = $raw->name;
  405. if (!empty($raw->modified_at)) {
  406. $stat['ts'] = strtotime($raw->modified_at);
  407. }
  408. if ($raw->type === 'folder') {
  409. $stat['mime'] = 'directory';
  410. $stat['size'] = 0;
  411. $stat['dirs'] = -1;
  412. } else {
  413. $stat['size'] = (int) $raw->size;
  414. if (!empty($raw->shared_link->url) && $raw->shared_link->access == 'open') {
  415. if ($url = $this->getSharedWebContentLink($raw)) {
  416. $stat['url'] = $url;
  417. }
  418. } elseif (!$this->disabledGetUrl) {
  419. $stat['url'] = '1';
  420. }
  421. }
  422. return $stat;
  423. }
  424. /**
  425. * Get thumbnail from Box.com.
  426. *
  427. * @param string $path
  428. * @param string $size
  429. *
  430. * @return string | boolean
  431. */
  432. protected function _bd_getThumbnail($path)
  433. {
  434. list(, $itemId) = $this->_bd_splitPath($path);
  435. try {
  436. $url = self::API_URL.'/files/'.$itemId.'/thumbnail.png?min_height=' . $this->tmbSize . '&min_width=' . $this->tmbSize;
  437. $contents = $this->_bd_fetch($url, true);
  438. return $contents;
  439. } catch (Exception $e) {
  440. return false;
  441. }
  442. }
  443. /**
  444. * Remove item.
  445. *
  446. * @param string $path file path
  447. *
  448. * @return bool
  449. **/
  450. protected function _bd_unlink($path, $type = null)
  451. {
  452. try {
  453. list(, $itemId) = $this->_bd_splitPath($path);
  454. if ($type == 'folders') {
  455. $url = self::API_URL.'/'.$type.'/'.$itemId.'?recursive=true';
  456. } else {
  457. $url = self::API_URL.'/'.$type.'/'.$itemId;
  458. }
  459. $curl = $this->_bd_prepareCurl(array(
  460. CURLOPT_URL => $url,
  461. CURLOPT_CUSTOMREQUEST => 'DELETE',
  462. ));
  463. //unlink or delete File or Folder in the Parent
  464. $this->_bd_curlExec($curl);
  465. } catch (Exception $e) {
  466. return $this->setError('Box error: '.$e->getMessage());
  467. }
  468. return true;
  469. }
  470. /*********************************************************************/
  471. /* OVERRIDE FUNCTIONS */
  472. /*********************************************************************/
  473. /**
  474. * Prepare
  475. * Call from elFinder::netmout() before volume->mount().
  476. *
  477. * @return array
  478. *
  479. * @author Naoki Sawada
  480. * @author Raja Sharma updating for Box
  481. **/
  482. public function netmountPrepare($options)
  483. {
  484. if (empty($options['client_id']) && defined('ELFINDER_BOX_CLIENTID')) {
  485. $options['client_id'] = ELFINDER_BOX_CLIENTID;
  486. }
  487. if (empty($options['client_secret']) && defined('ELFINDER_BOX_CLIENTSECRET')) {
  488. $options['client_secret'] = ELFINDER_BOX_CLIENTSECRET;
  489. }
  490. if (isset($options['pass']) && $options['pass'] === 'reauth') {
  491. $options['user'] = 'init';
  492. $options['pass'] = '';
  493. $this->session->remove('BoxTokens');
  494. }
  495. if (isset($options['id'])) {
  496. $this->session->set('nodeId', $options['id']);
  497. } elseif ($_id = $this->session->get('nodeId')) {
  498. $options['id'] = $_id;
  499. $this->session->set('nodeId', $_id);
  500. }
  501. try {
  502. if (empty($options['client_id']) || empty($options['client_secret'])) {
  503. return array('exit' => true, 'body' => '{msg:errNetMountNoDriver}');
  504. }
  505. if (isset($_GET['code'])) {
  506. try {
  507. // Obtain the token using the code received by the Box.com API
  508. $this->session->set('BoxTokens',
  509. $this->_bd_obtainAccessToken($options['client_id'], $options['client_secret'], $_GET['code']));
  510. $out = array(
  511. 'node' => $options['id'],
  512. 'json' => '{"protocol": "box", "mode": "done", "reset": 1}',
  513. 'bind' => 'netmount',
  514. );
  515. return array('exit' => 'callback', 'out' => $out);
  516. } catch (Exception $e) {
  517. $out = array(
  518. 'node' => $options['id'],
  519. 'json' => json_encode(array('error' => $e->getMessage())),
  520. );
  521. return array('exit' => 'callback', 'out' => $out);
  522. }
  523. } elseif (!empty($_GET['error'])) {
  524. $out = array(
  525. 'node' => $options['id'],
  526. 'json' => json_encode(array('error' => elFinder::ERROR_ACCESS_DENIED)),
  527. );
  528. return array('exit' => 'callback', 'out' => $out);
  529. }
  530. if ($options['user'] === 'init') {
  531. $this->token = $this->session->get('BoxTokens');
  532. if ($this->token) {
  533. try {
  534. $this->_bd_refreshToken();
  535. } catch (Exception $e) {
  536. $this->setError($e->getMessage());
  537. $this->token = null;
  538. $this->session->remove('BoxTokens');
  539. }
  540. }
  541. if (empty($this->token)) {
  542. $result = false;
  543. } else {
  544. $path = $options['path'];
  545. if ($path === '/' || $path === 'root') {
  546. $path = '0';
  547. }
  548. $result = $this->_bd_query($path, $fetch_self = false, $recursive = false);
  549. }
  550. if ($result === false) {
  551. $cdata = '';
  552. $innerKeys = array('cmd', 'host', 'options', 'pass', 'protocol', 'user');
  553. $this->ARGS = $_SERVER['REQUEST_METHOD'] === 'POST' ? $_POST : $_GET;
  554. foreach ($this->ARGS as $k => $v) {
  555. if (!in_array($k, $innerKeys)) {
  556. $cdata .= '&'.$k.'='.rawurlencode($v);
  557. }
  558. }
  559. if (empty($options['url'])) {
  560. $options['url'] = elFinder::getConnectorUrl();
  561. }
  562. $callback = $options['url']
  563. .'?cmd=netmount&protocol=box&host=box.com&user=init&pass=return&node='.$options['id'].$cdata;
  564. try {
  565. $this->session->set('BoxTokens', (object) array('token' => null));
  566. $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'));
  567. $url .= '&oauth_callback='.rawurlencode($callback);
  568. } catch (Exception $e) {
  569. return array('exit' => true, 'body' => '{msg:errAccess}');
  570. }
  571. $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.'\')">';
  572. $html .= '<script>
  573. $("#'.$options['id'].'").elfinder("instance").trigger("netmount", {protocol: "box", mode: "makebtn"});
  574. </script>';
  575. return array('exit' => true, 'body' => $html);
  576. } else {
  577. $folders = [];
  578. if ($result) {
  579. foreach ($result as $res) {
  580. if ($res->type == 'folder') {
  581. $folders[$res->id.' '] = $res->name;
  582. }
  583. }
  584. natcasesort($folders);
  585. }
  586. if ($options['pass'] === 'folders') {
  587. return ['exit' => true, 'folders' => $folders];
  588. }
  589. $folders = ['root' => 'My Box'] + $folders;
  590. $folders = json_encode($folders);
  591. $expires = empty($this->token->data->refresh_token) ? (int) $this->token->expires : 0;
  592. $json = '{"protocol": "box", "mode": "done", "folders": '.$folders.', "expires": '.$expires.'}';
  593. $html = 'Box.com';
  594. $html .= '<script>
  595. $("#'.$options['id'].'").elfinder("instance").trigger("netmount", '.$json.');
  596. </script>';
  597. return array('exit' => true, 'body' => $html);
  598. }
  599. }
  600. } catch (Exception $e) {
  601. return array('exit' => true, 'body' => '{msg:errNetMountNoDriver}');
  602. }
  603. if ($_aToken = $this->session->get('BoxTokens')) {
  604. $options['accessToken'] = json_encode($_aToken);
  605. } else {
  606. $this->setError(elFinder::ERROR_NETMOUNT, $options['host'], implode(' ', $this->error()));
  607. return array('exit' => true, 'error' => $this->error());
  608. }
  609. $this->session->remove('nodeId');
  610. unset($options['user'], $options['pass'], $options['id']);
  611. return $options;
  612. }
  613. /**
  614. * process of on netunmount
  615. * Drop `box` & rm thumbs.
  616. *
  617. * @param array $options
  618. *
  619. * @return bool
  620. */
  621. public function netunmount($netVolumes, $key)
  622. {
  623. if ($tmbs = glob(rtrim($this->options['tmbPath'], '\\/').DIRECTORY_SEPARATOR.$this->tmbPrefix.'*.png')) {
  624. foreach ($tmbs as $file) {
  625. unlink($file);
  626. }
  627. }
  628. return true;
  629. }
  630. /**
  631. * Return debug info for client.
  632. *
  633. * @return array
  634. **/
  635. public function debug()
  636. {
  637. $res = parent::debug();
  638. if (! empty($this->options['accessToken'])) {
  639. $res['accessToken'] = $this->options['accessToken'];
  640. }
  641. return $res;
  642. }
  643. /*********************************************************************/
  644. /* INIT AND CONFIGURE */
  645. /*********************************************************************/
  646. /**
  647. * Prepare FTP connection
  648. * Connect to remote server and check if credentials are correct, if so, store the connection id in $ftp_conn.
  649. *
  650. * @return bool
  651. *
  652. * @author Dmitry (dio) Levashov
  653. * @author Cem (DiscoFever)
  654. **/
  655. protected function init()
  656. {
  657. if (!$this->options['accessToken']) {
  658. return $this->setError('Required option `accessToken` is undefined.');
  659. }
  660. try {
  661. $this->token = json_decode($this->options['accessToken']);
  662. $this->_bd_refreshToken();
  663. } catch (Exception $e) {
  664. $this->token = null;
  665. $this->session->remove('BoxTokens');
  666. return $this->setError($e->getMessage());
  667. }
  668. if (empty($options['netkey'])) {
  669. // make net mount key
  670. $_tokenKey = isset($this->token->data->refresh_token) ? $this->token->data->refresh_token : $this->token->data->access_token;
  671. $this->netMountKey = md5(implode('-', array('box', $this->options['path'], $_tokenKey)));
  672. } else {
  673. $this->netMountKey = $options['netkey'];
  674. }
  675. // normalize root path
  676. if ($this->options['path'] == 'root') {
  677. $this->options['path'] = '/';
  678. }
  679. $this->root = $this->options['path'] = $this->_normpath($this->options['path']);
  680. $this->options['root'] == '' ? $this->options['root'] = 'Box.com' : $this->options['root'];
  681. if (empty($this->options['alias'])) {
  682. list(, $itemId) = $this->_bd_splitPath($this->options['path']);
  683. $this->options['alias'] = ($this->options['path'] === '/') ? $this->options['root'] :
  684. $this->_bd_query($itemId, $fetch_self = true)->name.'@Box.com';
  685. }
  686. $this->rootName = $this->options['alias'];
  687. $this->tmbPrefix = 'box'.base_convert($this->netMountKey, 10, 32);
  688. if (!empty($this->options['tmpPath'])) {
  689. if ((is_dir($this->options['tmpPath']) || mkdir($this->options['tmpPath'])) && is_writable($this->options['tmpPath'])) {
  690. $this->tmp = $this->options['tmpPath'];
  691. }
  692. }
  693. if (!$this->tmp && ($tmp = elFinder::getStaticVar('commonTempPath'))) {
  694. $this->tmp = $tmp;
  695. }
  696. // This driver dose not support `syncChkAsTs`
  697. $this->options['syncChkAsTs'] = false;
  698. // 'lsPlSleep' minmum 10 sec
  699. $this->options['lsPlSleep'] = max(10, $this->options['lsPlSleep']);
  700. // enable command archive
  701. $this->options['useRemoteArchive'] = true;
  702. return true;
  703. }
  704. /**
  705. * Configure after successfull mount.
  706. *
  707. * @author Dmitry (dio) Levashov
  708. **/
  709. protected function configure()
  710. {
  711. parent::configure();
  712. // fallback of $this->tmp
  713. if (!$this->tmp && $this->tmbPathWritable) {
  714. $this->tmp = $this->tmbPath;
  715. }
  716. }
  717. /*********************************************************************/
  718. /* FS API */
  719. /*********************************************************************/
  720. /**
  721. * Close opened connection.
  722. *
  723. * @author Dmitry (dio) Levashov
  724. **/
  725. public function umount()
  726. {
  727. }
  728. /**
  729. * Return fileinfo based on filename
  730. * For item ID based path file system
  731. * Please override if needed on each drivers.
  732. *
  733. * @param string $path file cache
  734. *
  735. * @return array
  736. */
  737. protected function isNameExists($path)
  738. {
  739. list($pid, $name, $parent) = $this->_bd_splitPath($path);
  740. // We can not use it because the search of Box.com there is a time lag.
  741. // ref. https://docs.box.com/reference#searching-for-content
  742. // > Note: If an item is added to Box then it becomes accessible through the search endpoint after ten minutes.
  743. /***
  744. $url = self::API_URL.'/search?limit=1&offset=0&content_types=name&ancestor_folder_ids='.rawurlencode($pid)
  745. .'&query='.rawurlencode('"'.$name.'"')
  746. .'fields='.self::FETCHFIELDS;
  747. $raw = $this->_bd_fetch($url);
  748. if (is_array($raw) && count($raw)) {
  749. return $this->_bd_parseRaw($raw);
  750. }
  751. ***/
  752. $phash = $this->encode($parent);
  753. // do not recursive search
  754. $searchExDirReg = $this->options['searchExDirReg'];
  755. $this->options['searchExDirReg'] = '/.*/';
  756. $search = $this->search($name, array(), $phash);
  757. $this->options['searchExDirReg'] = $searchExDirReg;
  758. if ($search) {
  759. return $search[0];
  760. }
  761. return false;
  762. }
  763. /**
  764. * Cache dir contents.
  765. *
  766. * @param string $path dir path
  767. *
  768. * @author Dmitry Levashov
  769. **/
  770. protected function cacheDir($path)
  771. {
  772. $this->dirsCache[$path] = array();
  773. $hasDir = false;
  774. if ($path == '/') {
  775. $items = $this->_bd_query('0', $fetch_self = true); // get root directory with folder & files
  776. $itemId = $items->id;
  777. } else {
  778. list(, $itemId) = $this->_bd_splitPath($path);
  779. }
  780. $res = $this->_bd_query($itemId);
  781. if ($res) {
  782. foreach ($res as $raw) {
  783. if ($stat = $this->_bd_parseRaw($raw)) {
  784. $itemPath = $this->_joinPath($path, $raw->id);
  785. $stat = $this->updateCache($itemPath, $stat);
  786. if (empty($stat['hidden'])) {
  787. if (!$hasDir && $stat['mime'] === 'directory') {
  788. $hasDir = true;
  789. }
  790. $this->dirsCache[$path][] = $itemPath;
  791. }
  792. }
  793. }
  794. }
  795. if (isset($this->sessionCache['subdirs'])) {
  796. $this->sessionCache['subdirs'][$path] = $hasDir;
  797. }
  798. return $this->dirsCache[$path];
  799. }
  800. /**
  801. * Copy file/recursive copy dir only in current volume.
  802. * Return new file path or false.
  803. *
  804. * @param string $src source path
  805. * @param string $dst destination dir path
  806. * @param string $name new file name (optionaly)
  807. *
  808. * @return string|false
  809. *
  810. * @author Dmitry (dio) Levashov
  811. * @author Naoki Sawada
  812. **/
  813. protected function copy($src, $dst, $name)
  814. {
  815. if ($res = $this->_copy($src, $dst, $name)) {
  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