elFinderVolumeOneDrive.class.php 60 KB

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