elFinderFlysystemGoogleDriveNetmount.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  1. <?php
  2. use League\Flysystem\Filesystem;
  3. use League\Flysystem\Adapter\Local;
  4. use League\Flysystem\Cached\CachedAdapter;
  5. use League\Flysystem\Cached\Storage\Adapter as ACache;
  6. use Hypweb\Flysystem\GoogleDrive\GoogleDriveAdapter;
  7. use Hypweb\Flysystem\Cached\Extra\Hasdir;
  8. use Hypweb\Flysystem\Cached\Extra\DisableEnsureParentDirectories;
  9. use Hypweb\elFinderFlysystemDriverExt\Driver as ExtDriver;
  10. elFinder::$netDrivers['googledrive'] = 'FlysystemGoogleDriveNetmount';
  11. if (!class_exists('elFinderVolumeFlysystemGoogleDriveCache', false)) {
  12. class elFinderVolumeFlysystemGoogleDriveCache extends ACache
  13. {
  14. use Hasdir;
  15. use DisableEnsureParentDirectories;
  16. }
  17. }
  18. class elFinderVolumeFlysystemGoogleDriveNetmount extends ExtDriver
  19. {
  20. public function __construct()
  21. {
  22. parent::__construct();
  23. $opts = array(
  24. 'acceptedName' => '#^[^/\\?*:|"<>]*[^./\\?*:|"<>]$#',
  25. 'rootCssClass' => 'elfinder-navbar-root-googledrive',
  26. 'gdAlias' => '%s@GDrive',
  27. 'gdCacheDir' => __DIR__ . '/.tmp',
  28. 'gdCachePrefix' => 'gd-',
  29. 'gdCacheExpire' => 600
  30. );
  31. $this->options = array_merge($this->options, $opts);
  32. }
  33. /**
  34. * Prepare driver before mount volume.
  35. * Return true if volume is ready.
  36. *
  37. * @return bool
  38. **/
  39. protected function init()
  40. {
  41. if (empty($this->options['icon'])) {
  42. $this->options['icon'] = true;
  43. }
  44. if ($res = parent::init()) {
  45. if ($this->options['icon'] === true) {
  46. unset($this->options['icon']);
  47. }
  48. // enable command archive
  49. $this->options['useRemoteArchive'] = true;
  50. }
  51. return $res;
  52. }
  53. /**
  54. * Prepare
  55. * Call from elFinder::netmout() before volume->mount()
  56. *
  57. * @param $options
  58. *
  59. * @return Array
  60. * @author Naoki Sawada
  61. */
  62. public function netmountPrepare($options)
  63. {
  64. if (empty($options['client_id']) && defined('ELFINDER_GOOGLEDRIVE_CLIENTID')) {
  65. $options['client_id'] = ELFINDER_GOOGLEDRIVE_CLIENTID;
  66. }
  67. if (empty($options['client_secret']) && defined('ELFINDER_GOOGLEDRIVE_CLIENTSECRET')) {
  68. $options['client_secret'] = ELFINDER_GOOGLEDRIVE_CLIENTSECRET;
  69. }
  70. if (!isset($options['pass'])) {
  71. $options['pass'] = '';
  72. }
  73. try {
  74. $client = new \Google_Client();
  75. $client->setClientId($options['client_id']);
  76. $client->setClientSecret($options['client_secret']);
  77. if ($options['pass'] === 'reauth') {
  78. $options['pass'] = '';
  79. $this->session->set('GoogleDriveAuthParams', [])->set('GoogleDriveTokens', []);
  80. } else if ($options['pass'] === 'googledrive') {
  81. $options['pass'] = '';
  82. }
  83. $options = array_merge($this->session->get('GoogleDriveAuthParams', []), $options);
  84. if (!isset($options['access_token'])) {
  85. $options['access_token'] = $this->session->get('GoogleDriveTokens', []);
  86. $this->session->remove('GoogleDriveTokens');
  87. }
  88. $aToken = $options['access_token'];
  89. $rootObj = $service = null;
  90. if ($aToken) {
  91. try {
  92. $client->setAccessToken($aToken);
  93. if ($client->isAccessTokenExpired()) {
  94. $aToken = array_merge($aToken, $client->fetchAccessTokenWithRefreshToken());
  95. $client->setAccessToken($aToken);
  96. }
  97. $service = new \Google_Service_Drive($client);
  98. $rootObj = $service->files->get('root');
  99. $options['access_token'] = $aToken;
  100. $this->session->set('GoogleDriveAuthParams', $options);
  101. } catch (Exception $e) {
  102. $aToken = [];
  103. $options['access_token'] = [];
  104. if ($options['user'] !== 'init') {
  105. $this->session->set('GoogleDriveAuthParams', $options);
  106. return array('exit' => true, 'error' => elFinder::ERROR_REAUTH_REQUIRE);
  107. }
  108. }
  109. }
  110. if ($options['user'] === 'init') {
  111. if (empty($options['url'])) {
  112. $options['url'] = elFinder::getConnectorUrl();
  113. }
  114. $callback = $options['url']
  115. . '?cmd=netmount&protocol=googledrive&host=1';
  116. $client->setRedirectUri($callback);
  117. if (!$aToken && empty($_GET['code'])) {
  118. $client->setScopes([Google_Service_Drive::DRIVE]);
  119. if (!empty($options['offline'])) {
  120. $client->setApprovalPrompt('force');
  121. $client->setAccessType('offline');
  122. }
  123. $url = $client->createAuthUrl();
  124. $html = '<input id="elf-volumedriver-googledrive-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 . '\')">';
  125. $html .= '<script>
  126. $("#' . $options['id'] . '").elfinder("instance").trigger("netmount", {protocol: "googledrive", mode: "makebtn"});
  127. </script>';
  128. if (empty($options['pass']) && $options['host'] !== '1') {
  129. $options['pass'] = 'return';
  130. $this->session->set('GoogleDriveAuthParams', $options);
  131. return array('exit' => true, 'body' => $html);
  132. } else {
  133. $out = array(
  134. 'node' => $options['id'],
  135. 'json' => '{"protocol": "googledrive", "mode": "makebtn", "body" : "' . str_replace($html, '"', '\\"') . '", "error" : "' . elFinder::ERROR_ACCESS_DENIED . '"}',
  136. 'bind' => 'netmount'
  137. );
  138. return array('exit' => 'callback', 'out' => $out);
  139. }
  140. } else {
  141. if (!empty($_GET['code'])) {
  142. $aToken = $client->fetchAccessTokenWithAuthCode($_GET['code']);
  143. $options['access_token'] = $aToken;
  144. $this->session->set('GoogleDriveTokens', $aToken)->set('GoogleDriveAuthParams', $options);
  145. $out = array(
  146. 'node' => $options['id'],
  147. 'json' => '{"protocol": "googledrive", "mode": "done", "reset": 1}',
  148. 'bind' => 'netmount'
  149. );
  150. return array('exit' => 'callback', 'out' => $out);
  151. }
  152. $folders = [];
  153. foreach ($service->files->listFiles([
  154. 'pageSize' => 1000,
  155. 'q' => 'trashed = false and mimeType = "application/vnd.google-apps.folder"'
  156. ]) as $f) {
  157. $folders[$f->getId()] = $f->getName();
  158. }
  159. natcasesort($folders);
  160. $folders = ['root' => $rootObj->getName()] + $folders;
  161. $folders = json_encode($folders);
  162. $json = '{"protocol": "googledrive", "mode": "done", "folders": ' . $folders . '}';
  163. $options['pass'] = 'return';
  164. $html = 'Google.com';
  165. $html .= '<script>
  166. $("#' . $options['id'] . '").elfinder("instance").trigger("netmount", ' . $json . ');
  167. </script>';
  168. $this->session->set('GoogleDriveAuthParams', $options);
  169. return array('exit' => true, 'body' => $html);
  170. }
  171. }
  172. } catch (Exception $e) {
  173. $this->session->remove('GoogleDriveAuthParams')->remove('GoogleDriveTokens');
  174. if (empty($options['pass'])) {
  175. return array('exit' => true, 'body' => '{msg:' . elFinder::ERROR_ACCESS_DENIED . '}' . ' ' . $e->getMessage());
  176. } else {
  177. return array('exit' => true, 'error' => [elFinder::ERROR_ACCESS_DENIED, $e->getMessage()]);
  178. }
  179. }
  180. if (!$aToken) {
  181. return array('exit' => true, 'error' => elFinder::ERROR_REAUTH_REQUIRE);
  182. }
  183. if ($options['path'] === '/') {
  184. $options['path'] = 'root';
  185. }
  186. try {
  187. $file = $service->files->get($options['path']);
  188. $options['alias'] = sprintf($this->options['gdAlias'], $file->getName());
  189. } catch (Google_Service_Exception $e) {
  190. $err = json_decode($e->getMessage(), true);
  191. if (isset($err['error']) && $err['error']['code'] == 404) {
  192. return array('exit' => true, 'error' => [elFinder::ERROR_TRGDIR_NOT_FOUND, $options['path']]);
  193. } else {
  194. return array('exit' => true, 'error' => $e->getMessage());
  195. }
  196. } catch (Exception $e) {
  197. return array('exit' => true, 'error' => $e->getMessage());
  198. }
  199. foreach (['host', 'user', 'pass', 'id', 'offline'] as $key) {
  200. unset($options[$key]);
  201. }
  202. return $options;
  203. }
  204. /**
  205. * process of on netunmount
  206. * Drop table `dropbox` & rm thumbs
  207. *
  208. * @param $netVolumes
  209. * @param $key
  210. *
  211. * @return bool
  212. * @internal param array $options
  213. */
  214. public function netunmount($netVolumes, $key)
  215. {
  216. $cache = $this->options['gdCacheDir'] . DIRECTORY_SEPARATOR . $this->options['gdCachePrefix'] . $this->netMountKey;
  217. if (file_exists($cache) && is_writeable($cache)) {
  218. unlink($cache);
  219. }
  220. if ($tmbs = glob($this->tmbPath . DIRECTORY_SEPARATOR . $this->netMountKey . '*')) {
  221. foreach ($tmbs as $file) {
  222. unlink($file);
  223. }
  224. }
  225. return true;
  226. }
  227. /**
  228. * "Mount" volume.
  229. * Return true if volume available for read or write,
  230. * false - otherwise
  231. *
  232. * @param array $opts
  233. *
  234. * @return bool
  235. * @author Naoki Sawada
  236. */
  237. public function mount(array $opts)
  238. {
  239. $creds = null;
  240. if (isset($opts['access_token'])) {
  241. $this->netMountKey = md5(join('-', array('googledrive', $opts['path'], (isset($opts['access_token']['refresh_token']) ? $opts['access_token']['refresh_token'] : $opts['access_token']['access_token']))));
  242. }
  243. $client = new \Google_Client();
  244. $client->setClientId($opts['client_id']);
  245. $client->setClientSecret($opts['client_secret']);
  246. if (!empty($opts['access_token'])) {
  247. $client->setAccessToken($opts['access_token']);
  248. }
  249. if ($client->isAccessTokenExpired()) {
  250. try {
  251. $creds = $client->fetchAccessTokenWithRefreshToken();
  252. } catch (LogicException $e) {
  253. $this->session->remove('GoogleDriveAuthParams');
  254. throw $e;
  255. }
  256. }
  257. $service = new \Google_Service_Drive($client);
  258. // If path is not set, use the root
  259. if (!isset($opts['path']) || $opts['path'] === '') {
  260. $opts['path'] = 'root';
  261. }
  262. $googleDrive = new GoogleDriveAdapter($service, $opts['path'], ['useHasDir' => true]);
  263. $opts['fscache'] = null;
  264. if ($this->options['gdCacheDir'] && is_writeable($this->options['gdCacheDir'])) {
  265. if ($this->options['gdCacheExpire']) {
  266. $opts['fscache'] = new elFinderVolumeFlysystemGoogleDriveCache(new Local($this->options['gdCacheDir']), $this->options['gdCachePrefix'] . $this->netMountKey, $this->options['gdCacheExpire']);
  267. }
  268. }
  269. if ($opts['fscache']) {
  270. $filesystem = new Filesystem(new CachedAdapter($googleDrive, $opts['fscache']));
  271. } else {
  272. $filesystem = new Filesystem($googleDrive);
  273. }
  274. $opts['driver'] = 'FlysystemExt';
  275. $opts['filesystem'] = $filesystem;
  276. $opts['separator'] = '/';
  277. $opts['checkSubfolders'] = true;
  278. if (!isset($opts['alias'])) {
  279. $opts['alias'] = 'GoogleDrive';
  280. }
  281. if ($res = parent::mount($opts)) {
  282. // update access_token of session data
  283. if ($creds) {
  284. $netVolumes = $this->session->get('netvolume');
  285. $netVolumes[$this->netMountKey]['access_token'] = array_merge($netVolumes[$this->netMountKey]['access_token'], $creds);
  286. $this->session->set('netvolume', $netVolumes);
  287. }
  288. }
  289. return $res;
  290. }
  291. /**
  292. * @inheritdoc
  293. */
  294. protected function tmbname($stat)
  295. {
  296. return $this->netMountKey . substr(substr($stat['hash'], strlen($this->id)), -38) . $stat['ts'] . '.png';
  297. }
  298. }