elFinderVolumeBox.class.php 54 KB

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