google.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537
  1. <?php
  2. /**
  3. * ownCloud
  4. *
  5. * @author Michael Gapczynski
  6. * @copyright 2012 Michael Gapczynski mtgap@owncloud.com
  7. *
  8. * This library is free software; you can redistribute it and/or
  9. * modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
  10. * License as published by the Free Software Foundation; either
  11. * version 3 of the License, or any later version.
  12. *
  13. * This library is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. * GNU AFFERO GENERAL PUBLIC LICENSE for more details.
  17. *
  18. * You should have received a copy of the GNU Affero General Public
  19. * License along with this library. If not, see <http://www.gnu.org/licenses/>.
  20. */
  21. require_once 'Google/common.inc.php';
  22. class OC_Filestorage_Google extends OC_Filestorage_Common {
  23. private $consumer;
  24. private $oauth_token;
  25. private $sig_method;
  26. private $entries;
  27. private static $tempFiles = array();
  28. public function __construct($arguments) {
  29. $consumer_key = isset($arguments['consumer_key']) ? $arguments['consumer_key'] : 'anonymous';
  30. $consumer_secret = isset($arguments['consumer_secret']) ? $arguments['consumer_secret'] : 'anonymous';
  31. $this->consumer = new OAuthConsumer($consumer_key, $consumer_secret);
  32. $this->oauth_token = new OAuthToken($arguments['token'], $arguments['token_secret']);
  33. $this->sig_method = new OAuthSignatureMethod_HMAC_SHA1();
  34. $this->entries = array();
  35. }
  36. private function sendRequest($uri, $httpMethod, $postData = null, $extraHeaders = null, $isDownload = false, $returnHeaders = false, $isContentXML = true, $returnHTTPCode = false) {
  37. $uri = trim($uri);
  38. // create an associative array from each key/value url query param pair.
  39. $params = array();
  40. $pieces = explode('?', $uri);
  41. if (isset($pieces[1])) {
  42. $params = explode_assoc('=', '&', $pieces[1]);
  43. }
  44. // urlencode each url parameter key/value pair
  45. $tempStr = $pieces[0];
  46. foreach ($params as $key => $value) {
  47. $tempStr .= '&' . urlencode($key) . '=' . urlencode($value);
  48. }
  49. $uri = preg_replace('/&/', '?', $tempStr, 1);
  50. $request = OAuthRequest::from_consumer_and_token($this->consumer, $this->oauth_token, $httpMethod, $uri, $params);
  51. $request->sign_request($this->sig_method, $this->consumer, $this->oauth_token);
  52. $auth_header = $request->to_header();
  53. $headers = array($auth_header, 'GData-Version: 3.0');
  54. if ($isContentXML) {
  55. $headers = array_merge($headers, array('Content-Type: application/atom+xml'));
  56. }
  57. if (is_array($extraHeaders)) {
  58. $headers = array_merge($headers, $extraHeaders);
  59. }
  60. $curl = curl_init($uri);
  61. curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
  62. curl_setopt($curl, CURLOPT_FAILONERROR, false);
  63. curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
  64. switch ($httpMethod) {
  65. case 'GET':
  66. curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
  67. break;
  68. case 'POST':
  69. curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
  70. curl_setopt($curl, CURLOPT_POST, 1);
  71. curl_setopt($curl, CURLOPT_POSTFIELDS, $postData);
  72. break;
  73. case 'PUT':
  74. $headers[] = 'If-Match: *';
  75. curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
  76. curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $httpMethod);
  77. curl_setopt($curl, CURLOPT_POSTFIELDS, $postData);
  78. break;
  79. case 'DELETE':
  80. $headers[] = 'If-Match: *';
  81. curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
  82. curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $httpMethod);
  83. break;
  84. default:
  85. curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
  86. }
  87. if ($isDownload) {
  88. $tmpFile = OC_Helper::tmpFile();
  89. $handle = fopen($tmpFile, 'w');
  90. curl_setopt($curl, CURLOPT_FILE, $handle);
  91. }
  92. if ($returnHeaders) {
  93. curl_setopt($curl, CURLOPT_HEADER, true);
  94. }
  95. $result = curl_exec($curl);
  96. $httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
  97. curl_close($curl);
  98. if ($result) {
  99. // TODO https://developers.google.com/google-apps/documents-list/#handling_api_errors
  100. // TODO Log error messages
  101. if ($httpCode <= 308) {
  102. if ($isDownload) {
  103. return $tmpFile;
  104. } else if ($returnHTTPCode) {
  105. return array('result' => $result, 'code' => $httpCode);
  106. } else {
  107. return $result;
  108. }
  109. }
  110. }
  111. return false;
  112. }
  113. private function getFeed($feedUri, $httpMethod, $postData = null) {
  114. $result = $this->sendRequest($feedUri, $httpMethod, $postData);
  115. if ($result) {
  116. $dom = new DOMDocument();
  117. $dom->loadXML($result);
  118. return $dom;
  119. }
  120. return false;
  121. }
  122. private function getResource($path) {
  123. $file = basename($path);
  124. if (array_key_exists($file, $this->entries)) {
  125. return $this->entries[$file];
  126. } else {
  127. // Strip the file extension; file could be a native Google Docs resource
  128. if ($pos = strpos($file, '.')) {
  129. $title = substr($file, 0, $pos);
  130. $dom = $this->getFeed('https://docs.google.com/feeds/default/private/full?showfolders=true&title='.$title, 'GET');
  131. // Check if request was successful and entry exists
  132. if ($dom && $entry = $dom->getElementsByTagName('entry')->item(0)) {
  133. $this->entries[$file] = $entry;
  134. return $entry;
  135. }
  136. }
  137. $dom = $this->getFeed('https://docs.google.com/feeds/default/private/full?showfolders=true&title='.$file, 'GET');
  138. // Check if request was successful and entry exists
  139. if ($dom && $entry = $dom->getElementsByTagName('entry')->item(0)) {
  140. $this->entries[$file] = $entry;
  141. return $entry;
  142. }
  143. return false;
  144. }
  145. }
  146. private function getExtension($entry) {
  147. $mimetype = $this->getMimeType('', $entry);
  148. switch ($mimetype) {
  149. case 'httpd/unix-directory':
  150. return '';
  151. case 'application/vnd.oasis.opendocument.text':
  152. return 'odt';
  153. case 'application/vnd.oasis.opendocument.spreadsheet':
  154. return 'ods';
  155. case 'application/vnd.oasis.opendocument.presentation':
  156. return 'pptx';
  157. case 'text/html':
  158. return 'html';
  159. default:
  160. return 'html';
  161. }
  162. }
  163. public function mkdir($path) {
  164. $collection = dirname($path);
  165. // Check if path parent is root directory
  166. if ($collection == '/' || $collection == '\.' || $collection == '.') {
  167. $uri = 'https://docs.google.com/feeds/default/private/full';
  168. // Get parent content link
  169. } else if ($dom = $this->getResource(basename($dir))) {
  170. $uri = $dom->getElementsByTagName('content')->item(0)->getAttribute('src');
  171. }
  172. if (isset($uri)) {
  173. $title = basename($path);
  174. // Construct post data
  175. $postData = '<?xml version="1.0" encoding="UTF-8"?>';
  176. $postData .= '<entry xmlns="http://www.w3.org/2005/Atom">';
  177. $postData .= '<category scheme="http://schemas.google.com/g/2005#kind" term="http://schemas.google.com/docs/2007#folder"/>';
  178. $postData .= '<title>'.$title.'</title>';
  179. $postData .= '</entry>';
  180. if ($dom = $this->sendRequest($uri, 'POST', $postData)) {
  181. return true;
  182. }
  183. }
  184. return false;
  185. }
  186. public function rmdir($path) {
  187. return $this->unlink($path);
  188. }
  189. public function opendir($path) {
  190. if ($path == '' || $path == '/') {
  191. $next = 'https://docs.google.com/feeds/default/private/full/folder%3Aroot/contents';
  192. } else {
  193. if ($entry = $this->getResource($path)) {
  194. $next = $entry->getElementsByTagName('content')->item(0)->getAttribute('src');
  195. } else {
  196. return false;
  197. }
  198. }
  199. $files = array();
  200. while ($next) {
  201. $dom = $this->getFeed($next, 'GET');
  202. $links = $dom->getElementsByTagName('link');
  203. foreach ($links as $link) {
  204. if ($link->getAttribute('rel') == 'next') {
  205. $next = $link->getAttribute('src');
  206. break;
  207. } else {
  208. $next = false;
  209. }
  210. }
  211. $entries = $dom->getElementsByTagName('entry');
  212. foreach ($entries as $entry) {
  213. $name = $entry->getElementsByTagName('title')->item(0)->nodeValue;
  214. // Google Docs resources don't always include extensions in title
  215. if (!strpos($name, '.')) {
  216. $extension = $this->getExtension($entry);
  217. if ($extension != '') {
  218. $name .= '.'.$extension;
  219. }
  220. }
  221. $files[] = $name;
  222. // Cache entry for future use
  223. $this->entries[$name] = $entry;
  224. }
  225. }
  226. OC_FakeDirStream::$dirs['google'] = $files;
  227. return opendir('fakedir://google');
  228. }
  229. public function stat($path) {
  230. if ($path == '' || $path == '/') {
  231. $stat['size'] = $this->free_space($path);
  232. $stat['atime'] = time();
  233. $stat['mtime'] = time();
  234. $stat['ctime'] = time();
  235. } else if ($entry = $this->getResource($path)) {
  236. // NOTE: Native resources don't have a file size
  237. $stat['size'] = $entry->getElementsByTagNameNS('http://schemas.google.com/g/2005', 'quotaBytesUsed')->item(0)->nodeValue;
  238. // if (isset($atime = $entry->getElementsByTagNameNS('http://schemas.google.com/g/2005', 'lastViewed')->item(0)->nodeValue))
  239. // $stat['atime'] = strtotime($entry->getElementsByTagNameNS('http://schemas.google.com/g/2005', 'lastViewed')->item(0)->nodeValue);
  240. $stat['mtime'] = strtotime($entry->getElementsByTagName('updated')->item(0)->nodeValue);
  241. $stat['ctime'] = strtotime($entry->getElementsByTagName('published')->item(0)->nodeValue);
  242. }
  243. if (isset($stat)) {
  244. return $stat;
  245. }
  246. return false;
  247. }
  248. public function filetype($path) {
  249. if ($path == '' || $path == '/') {
  250. return 'dir';
  251. } else if ($entry = $this->getResource($path)) {
  252. $categories = $entry->getElementsByTagName('category');
  253. foreach ($categories as $category) {
  254. if ($category->getAttribute('scheme') == 'http://schemas.google.com/g/2005#kind') {
  255. $type = $category->getAttribute('label');
  256. if (strlen(strstr($type, 'folder')) > 0) {
  257. return 'dir';
  258. } else {
  259. return 'file';
  260. }
  261. }
  262. }
  263. }
  264. return false;
  265. }
  266. public function is_readable($path) {
  267. return true;
  268. }
  269. public function is_writable($path) {
  270. if ($path == '' || $path == '/') {
  271. return true;
  272. } else if ($entry = $this->getResource($path)) {
  273. // Check if edit or edit-media links exist
  274. $links = $entry->getElementsByTagName('link');
  275. foreach ($links as $link) {
  276. if ($link->getAttribute('rel') == 'edit') {
  277. return true;
  278. } else if ($link->getAttribute('rel') == 'edit-media') {
  279. return true;
  280. }
  281. }
  282. }
  283. return false;
  284. }
  285. public function file_exists($path) {
  286. if ($path == '' || $path == '/') {
  287. return true;
  288. } else if ($this->getResource($path)) {
  289. return true;
  290. }
  291. return false;
  292. }
  293. public function unlink($path) {
  294. // Get resource self link to trash resource
  295. if ($entry = $this->getResource($path)) {
  296. $links = $entry->getElementsByTagName('link');
  297. foreach ($links as $link) {
  298. if ($link->getAttribute('rel') == 'self') {
  299. $uri = $link->getAttribute('href');
  300. break;
  301. }
  302. }
  303. }
  304. if (isset($uri)) {
  305. $this->sendRequest($uri, 'DELETE');
  306. return true;
  307. }
  308. return false;
  309. }
  310. public function rename($path1, $path2) {
  311. if ($entry = $this->getResource($path1)) {
  312. $collection = dirname($path2);
  313. if (dirname($path1) == $collection) {
  314. // Get resource edit link to rename resource
  315. $etag = $entry->getAttribute('gd:etag');
  316. $links = $entry->getElementsByTagName('link');
  317. foreach ($links as $link) {
  318. if ($link->getAttribute('rel') == 'edit') {
  319. $uri = $link->getAttribute('href');
  320. break;
  321. }
  322. }
  323. $title = basename($path);
  324. // Construct post data
  325. $postData = '<?xml version="1.0" encoding="UTF-8"?>';
  326. $postData .= '<entry xmlns="http://www.w3.org/2005/Atom" xmlns:docs="http://schemas.google.com/docs/2007" xmlns:gd="http://schemas.google.com/g/2005" gd:etag='.$etag.'>';
  327. $postData .= '<title>'.$title.'</title>';
  328. $postData .= '</entry>';
  329. $this->sendRequest($uri, 'PUT', $postData);
  330. return true;
  331. } else {
  332. // Move to different collection
  333. if ($collectionEntry = $this->getResource($collection)) {
  334. $feedUri = $colelctionEntry->getElementsByTagName('content')->item(0)->getAttribute('src');
  335. // Construct post data
  336. $postData = '<?xml version="1.0" encoding="UTF-8"?>';
  337. $postData .= '<entry xmlns="http://www.w3.org/2005/Atom">';
  338. $postData .= '<id>'.$entry->getElementsByTagName('id')->item(0).'</id>';
  339. $postData .= '</entry>';
  340. $this->sendRequest($uri, 'POST', $postData);
  341. return true;
  342. }
  343. }
  344. }
  345. return false;
  346. }
  347. public function fopen($path, $mode) {
  348. switch ($mode) {
  349. case 'r':
  350. case 'rb':
  351. if ($entry = $this->getResource($path)) {
  352. $extension = $this->getExtension($entry);
  353. $downloadUri = $entry->getElementsByTagName('content')->item(0)->getAttribute('src');
  354. // TODO Non-native documents don't need these additional parameters
  355. $downloadUri .= '&exportFormat='.$extension.'&format='.$extension;
  356. $tmpFile = $this->sendRequest($downloadUri, 'GET', null, null, true);
  357. return fopen($tmpFile, 'r');
  358. }
  359. case 'w':
  360. case 'wb':
  361. case 'a':
  362. case 'ab':
  363. case 'r+':
  364. case 'w+':
  365. case 'wb+':
  366. case 'a+':
  367. case 'x':
  368. case 'x+':
  369. case 'c':
  370. case 'c+':
  371. if (strrpos($path,'.') !== false) {
  372. $ext = substr($path,strrpos($path,'.'));
  373. } else {
  374. $ext = '';
  375. }
  376. $tmpFile = OC_Helper::tmpFile($ext);
  377. OC_CloseStreamWrapper::$callBacks[$tmpFile] = array($this, 'writeBack');
  378. if ($this->file_exists($path)) {
  379. $source = $this->fopen($path, 'r');
  380. file_put_contents($tmpFile, $source);
  381. }
  382. self::$tempFiles[$tmpFile] = $path;
  383. return fopen('close://'.$tmpFile, $mode);
  384. }
  385. return false;
  386. }
  387. public function writeBack($tmpFile) {
  388. if (isset(self::$tempFiles[$tmpFile])) {
  389. $this->uploadFile($tmpFile, self::$tempFiles[$tmpFile]);
  390. unlink($tmpFile);
  391. }
  392. }
  393. private function uploadFile($path, $target) {
  394. $entry = $this->getResource($target);
  395. if (!$entry) {
  396. if (dirname($target) == '.' || dirname($target) == '/') {
  397. $uploadUri = 'https://docs.google.com/feeds/upload/create-session/default/private/full/folder%3Aroot/contents';
  398. } else {
  399. $entry = $this->getResource(dirname($target));
  400. }
  401. }
  402. if (!isset($uploadUri) && $entry) {
  403. $etag = $entry->getAttribute('gd:etag');
  404. $links = $entry->getElementsByTagName('link');
  405. foreach ($links as $link) {
  406. if ($link->getAttribute('rel') == 'http://schemas.google.com/g/2005#resumable-create-media') {
  407. $uploadUri = $link->getAttribute('href');
  408. break;
  409. }
  410. }
  411. }
  412. if (isset($uploadUri) && $handle = fopen($path, 'r')) {
  413. $uploadUri .= '?convert=false';
  414. $mimetype = OC_Helper::getMimeType($path);
  415. $size = filesize($path);
  416. $headers = array('X-Upload-Content-Type: ' => $mimetype, 'X-Upload-Content-Length: ' => $size);
  417. $postData = '<?xml version="1.0" encoding="UTF-8"?>';
  418. $postData .= '<entry xmlns="http://www.w3.org/2005/Atom" xmlns:docs="http://schemas.google.com/docs/2007">';
  419. $postData .= '<title>'.basename($target).'</title>';
  420. $postData .= '</entry>';
  421. $result = $this->sendRequest($uploadUri, 'POST', $postData, $headers, false, true);
  422. if ($result) {
  423. // Get location to upload file
  424. if (preg_match('@^Location: (.*)$@m', $result, $matches)) {
  425. $uploadUri = trim($matches[1]);
  426. }
  427. } else {
  428. return false;
  429. }
  430. // 512 kB chunks
  431. $chunkSize = 524288;
  432. $i = 0;
  433. while (!feof($handle)) {
  434. if ($i + $chunkSize > $size) {
  435. if ($i == 0) {
  436. $chunkSize = $size;
  437. } else {
  438. $chunkSize = $size % $i;
  439. }
  440. }
  441. $end = $i + $chunkSize - 1;
  442. $headers = array('Content-Length: '.$chunkSize, 'Content-Type: '.$mimetype, 'Content-Range: bytes '.$i.'-'.$end.'/'.$size);
  443. $postData = fread($handle, $chunkSize);
  444. $result = $this->sendRequest($uploadUri, 'PUT', $postData, $headers, false, true, false, true);
  445. if ($result['code'] == '308') {
  446. if (preg_match('@^Location: (.*)$@m', $result['result'], $matches)) {
  447. // Get next location to upload file chunk
  448. $uploadUri = trim($matches[1]);
  449. }
  450. $i += $chunkSize;
  451. } else {
  452. return false;
  453. }
  454. }
  455. // TODO Wait for resource entry
  456. }
  457. }
  458. public function getMimeType($path, $entry = null) {
  459. // Entry can be passed, because extension is required for opendir and the entry can't be cached without the extension
  460. if ($entry == null) {
  461. if ($path == '' || $path == '/') {
  462. return 'httpd/unix-directory';
  463. } else {
  464. $entry = $this->getResource($path);
  465. }
  466. }
  467. if ($entry) {
  468. $mimetype = $entry->getElementsByTagName('content')->item(0)->getAttribute('type');
  469. // Native Google Docs resources often default to text/html, but it may be more useful to default to a corresponding ODF mimetype
  470. // Collections get reported as application/atom+xml, make sure it actually is a folder and fix the mimetype
  471. if ($mimetype == 'text/html' || $mimetype == 'application/atom+xml;type=feed') {
  472. $categories = $entry->getElementsByTagName('category');
  473. foreach ($categories as $category) {
  474. if ($category->getAttribute('scheme') == 'http://schemas.google.com/g/2005#kind') {
  475. $type = $category->getAttribute('label');
  476. if (strlen(strstr($type, 'folder')) > 0) {
  477. return 'httpd/unix-directory';
  478. } else if (strlen(strstr($type, 'document')) > 0) {
  479. return 'application/vnd.oasis.opendocument.text';
  480. } else if (strlen(strstr($type, 'spreadsheet')) > 0) {
  481. return 'application/vnd.oasis.opendocument.spreadsheet';
  482. } else if (strlen(strstr($type, 'presentation')) > 0) {
  483. return 'application/vnd.oasis.opendocument.presentation';
  484. } else if (strlen(strstr($type, 'drawing')) > 0) {
  485. return 'application/vnd.oasis.opendocument.graphics';
  486. } else {
  487. // If nothing matches return text/html, all native Google Docs resources can be exported as text/html
  488. return 'text/html';
  489. }
  490. }
  491. }
  492. }
  493. return $mimetype;
  494. }
  495. return false;
  496. }
  497. public function free_space($path) {
  498. if ($dom = $this->getFeed('https://docs.google.com/feeds/metadata/default', 'GET')) {
  499. // NOTE: Native Google Docs resources don't count towards quota
  500. $total = $dom->getElementsByTagNameNS('http://schemas.google.com/g/2005', 'quotaBytesTotal')->item(0)->nodeValue;
  501. $used = $dom->getElementsByTagNameNS('http://schemas.google.com/g/2005', 'quotaBytesUsed')->item(0)->nodeValue;
  502. return $total - $used;
  503. }
  504. return false;
  505. }
  506. public function touch($path, $mtime = null) {
  507. }
  508. }