elFinderVolumeOneDrive.class.php 60 KB

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