opendrive.php 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466
  1. <?php
  2. # Debug
  3. $DEBUG = 0;
  4. if ($_ENV['DEBUG']) {
  5. $DEBUG = intval($_ENV['DEBUG']);
  6. if (!$DEBUG) {
  7. $DEBUG = 1;
  8. }
  9. }
  10. # On-disk config
  11. require_once '.secrets';
  12. # Config
  13. global $API_BASE;
  14. global $API_VERSION;
  15. global $API_CHUNK_SIZE;
  16. $API_BASE = 'https://dev.opendrive.com/api/v1';
  17. $API_VERSION = 10;
  18. $API_CHUNK_SIZE = 250 * 1024 * 1024;
  19. # PHP version support
  20. if (!function_exists('curl_file_create')) {
  21. function curl_file_create($filename, $mimetype = '', $postname = '') {
  22. return '@' . $filename . ';filename=' .
  23. ($postname ?: basename($filename)) .
  24. ($mimetype ? ';type=' . $mimetype : '');
  25. }
  26. }
  27. # Open the DB connection
  28. function dbOpen() {
  29. global $DB_STRING;
  30. global $DB_USER;
  31. global $DB_PASSWD;
  32. try {
  33. $dbh = new PDO($DB_STRING, $DB_USER, $DB_PASSWD);
  34. } catch (PDOException $e) {
  35. die('DB error: ' . $e->getMessage() . "\n");
  36. }
  37. return $dbh;
  38. }
  39. # Cleanup a path for better matching at OpenDrive
  40. function pathCleanup($path) {
  41. $path = preg_replace('/\/+$/', '', $path);
  42. $path = preg_replace('/^\/+/', '', $path);
  43. return $path;
  44. }
  45. # Return the clean parent path of a provided path
  46. function parentPath($path) {
  47. return dirname(pathCleanup($path));
  48. }
  49. # Return the clean base name of a provided path
  50. function basePath($path) {
  51. return basename(pathCleanup($path));
  52. }
  53. function curlPostRaw($url, $data, $header = NULL) {
  54. global $API_BASE;
  55. global $CA_PATH;
  56. global $DEBUG;
  57. # Setup cURL
  58. $ch = curl_init($API_BASE . $url);
  59. curl_setopt_array($ch, array(
  60. CURLOPT_CAINFO => $CA_PATH,
  61. CURLOPT_POST => true,
  62. CURLOPT_RETURNTRANSFER => true,
  63. CURLOPT_POSTFIELDS => $data
  64. ));
  65. if ($DEBUG >= 3) {
  66. curl_setopt($ch, CURLOPT_VERBOSE, true);
  67. }
  68. if ($header != NULL) {
  69. if (!is_array($header)) {
  70. $header = array($header);
  71. }
  72. curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
  73. }
  74. # Send the request
  75. if ($DEBUG >= 2) {
  76. echo 'Request: ' . $url . "\n";
  77. print_r($data);
  78. echo "\n";
  79. }
  80. $response = curl_exec($ch);
  81. # Check for errors
  82. if ($response === FALSE){
  83. die(curl_error($ch));
  84. }
  85. # Return
  86. if ($DEBUG >= 4) {
  87. echo "Response headers:\n";
  88. print_r(curl_getinfo($ch));
  89. echo "Response body:\n";
  90. print_r($response);
  91. echo "\n\n======================================\n\n\n";
  92. }
  93. return($response);
  94. }
  95. # POST the provided data to OpenDrive
  96. function curlPost($url, $data) {
  97. $data = json_encode($data);
  98. $response = curlPostRaw($url, $data, 'Content-Type: application/json');
  99. $responseData = json_decode($response, true);
  100. if ($DEBUG >= 3) {
  101. echo "Response Data:\n";
  102. print_r($responseData);
  103. }
  104. return($responseData);
  105. }
  106. # GET from OpenDrive
  107. function curlGet($url) {
  108. global $API_BASE;
  109. global $CA_PATH;
  110. global $DEBUG;
  111. # Setup cURL
  112. $ch = curl_init($API_BASE . $url);
  113. curl_setopt_array($ch, array(
  114. CURLOPT_CAINFO => $CA_PATH,
  115. CURLOPT_RETURNTRANSFER => true
  116. ));
  117. if ($DEBUG >= 3) {
  118. curl_setopt($ch, CURLOPT_VERBOSE, true);
  119. }
  120. # Send the request
  121. if ($DEBUG >= 2) {
  122. echo 'Request: ' . $url . "\n";
  123. print_r($data);
  124. echo "\n";
  125. }
  126. $response = curl_exec($ch);
  127. # Check for errors
  128. if ($response === FALSE){
  129. die(curl_error($ch));
  130. }
  131. # Return
  132. $responseData = json_decode($response, true);
  133. return($responseData);
  134. }
  135. # Login to OD and return the SessionID
  136. function login() {
  137. global $API_VERSION;
  138. global $OD_USER;
  139. global $OD_PASSWD;
  140. $data = array(
  141. 'username' => $OD_USER,
  142. 'passwd' => $OD_PASSWD,
  143. 'version' => $API_VERSION
  144. );
  145. $response = curlPost('/session/login.json', $data);
  146. # Check the result
  147. if ($response['SessionID']) {
  148. return $response['SessionID'];
  149. }
  150. return false;
  151. }
  152. # Logout of OpenDrive
  153. function logout($session) {
  154. $data = array(
  155. 'session_id' => $session
  156. );
  157. $response = curlPost('/session/logout.json', $data);
  158. # Check the result
  159. if ($response['result'] == 'true') {
  160. return true;
  161. }
  162. return false;
  163. }
  164. # Return the ID of a folder
  165. function folderID($session, $path) {
  166. $data = array(
  167. 'session_id' => $session,
  168. 'path' => $path
  169. );
  170. $response = curlPost('/folder/idbypath.json', $data);
  171. # Check the result
  172. if ($response['FolderId']) {
  173. return($response['FolderId']);
  174. }
  175. return false;
  176. }
  177. # Find the parent ID for a given path
  178. function parentID($session, $path) {
  179. $parent = parentPath($path);
  180. $parentID = 0;
  181. if ($parent != '.') {
  182. $parentID = folderID($session, $parent);
  183. }
  184. return $parentID;
  185. }
  186. # Create a folder
  187. function mkFolder($session, $path) {
  188. global $DEBUG;
  189. # Find the parent ID (if any)
  190. $parentID = parentID($session, $path);
  191. if ($parentID === false) {
  192. if ($DEBUG) {
  193. echo 'Invalid parent for path: ' . $path . "\n";
  194. }
  195. return false;
  196. }
  197. # POST
  198. $data = array(
  199. 'session_id' => $session,
  200. 'folder_name' => basePath($path),
  201. 'folder_sub_parent' => $parentID,
  202. 'folder_is_public' => 0
  203. );
  204. $response = curlPost('/folder.json', $data);
  205. # Check the result
  206. if ($response['FolderId']) {
  207. return($response['FolderId']);
  208. }
  209. return false;
  210. }
  211. # Trash a folder
  212. function rmFolder($session, $path) {
  213. $id = folderID($session, $path);
  214. if (!$id) {
  215. return false;
  216. }
  217. $data = array(
  218. 'session_id' => $session,
  219. 'folder_id' => $id
  220. );
  221. $response = curlPost('/folder/trash.json', $data);
  222. # Check the result
  223. if ($response['DirUpdateTime']) {
  224. return true;
  225. }
  226. return false;
  227. }
  228. # Return the ID of a file
  229. function fileID($session, $path) {
  230. $data = array(
  231. 'session_id' => $session,
  232. 'path' => $path
  233. );
  234. $response = curlPost('/file/idbypath.json', $data);
  235. # Check the result
  236. if ($response['FileId']) {
  237. return($response['FileId']);
  238. }
  239. return false;
  240. }
  241. # Return all file metadata
  242. function fileInfo($session, $path) {
  243. $id = fileID($session, $path);
  244. if (!$id) {
  245. return false;
  246. }
  247. # GET
  248. $response = curlGet('/file/info.json/' . $session . '/' . $id);
  249. # Check the result
  250. if ($response['FileId']) {
  251. return($response);
  252. }
  253. return false;
  254. }
  255. # Upload the provided file to the given path
  256. function fileUpload($session, $path, $file) {
  257. global $DEBUG;
  258. global $API_CHUNK_SIZE;
  259. # Find the local file
  260. $stat = @stat($file);
  261. if ($stat === false) {
  262. if ($DEBUG) {
  263. echo 'Unable to stat: ' . $file . "\n";
  264. }
  265. return false;
  266. }
  267. # Find the parent ID
  268. $parentID = parentID($session, $path);
  269. if ($parentID === false) {
  270. if ($DEBUG) {
  271. echo 'No parent for path: ' . $path . "\n";
  272. }
  273. return false;
  274. }
  275. # Allocate
  276. $data = array(
  277. 'session_id' => $session,
  278. 'folder_id' => $parentID,
  279. 'file_name' => basePath($path),
  280. 'file_size' => $stat['size']
  281. );
  282. $response = curlPost('/upload/create_file.json', $data);
  283. $id = $response['FileId'];
  284. if (!$id) {
  285. if ($DEBUG) {
  286. echo 'Unable to allocate: ' . $path . "\n";
  287. }
  288. return false;
  289. }
  290. # Open
  291. $data = array(
  292. 'session_id' => $session,
  293. 'file_id' => $id,
  294. 'file_size' => $stat['size']
  295. );
  296. $response = curlPost('/upload/open_file_upload.json', $data);
  297. $tmpPath = $response['TempLocation'];
  298. if (!$tmpPath) {
  299. if ($DEBUG) {
  300. echo 'Unable to open: ' . $path . "\n";
  301. }
  302. return false;
  303. }
  304. # Split if needed
  305. $tempDir = false;
  306. $files = array();
  307. if ($stat['size'] > $API_CHUNK_SIZE) {
  308. if ($DEBUG) {
  309. echo 'Splitting file: ' . $file . ' (' . $API_CHUNK_SIZE . '/' . $stat['size'] . ")\n";
  310. }
  311. # Create a temporary directory
  312. $tempDir = trim(shell_exec('mktemp -d'));
  313. if (!is_dir($tempDir)) {
  314. echo "Unable to create temp directory\n";
  315. return false;
  316. }
  317. # Split into chunk-sized parts
  318. shell_exec('cd ' . escapeshellarg($tempDir) .
  319. ' && split -b ' . escapeshellarg($API_CHUNK_SIZE) . ' ' . escapeshellarg($file));
  320. # Find all their paths
  321. $fh = opendir($tempDir);
  322. if (!$fh) {
  323. echo 'Unable to open temp directory: ' . $tempDir . "\n";
  324. return false;
  325. }
  326. while (($chunk = readdir($fh)) !== false) {
  327. if (preg_match('/^x\w+$/', $chunk)) {
  328. $files[] = $tempDir . '/' . $chunk;
  329. }
  330. }
  331. unset($chunk);
  332. # Cleanup
  333. closedir($fh);
  334. unset($fh);
  335. } else {
  336. $files[] = $file;
  337. }
  338. # Sort the list to ensure the chunks are uploaded in order
  339. sort($files);
  340. # Upload
  341. $offset = 0;
  342. foreach ($files as $chunk) {
  343. if ($DEBUG > 1) {
  344. echo 'Uploading chunk: ' . $chunk . "\n";
  345. }
  346. # Find the chunk size
  347. $chunkStat = @stat($chunk);
  348. if ($chunkStat === false) {
  349. echo 'Unable to stat chunk: ' . $chunk . "\n";
  350. return false;
  351. }
  352. # Setup cURL
  353. $cfile = curl_file_create($chunk, 'application/octet-stream', basePath($file));
  354. $data = array(
  355. 'session_id' => $session,
  356. 'file_id' => $id,
  357. 'temp_location' => $tmpPath,
  358. 'chunk_offset' => $offset,
  359. 'chunk_size' => $chunkStat['size'],
  360. 'file_data' => $cfile
  361. );
  362. # Upload
  363. $response = curlPostRaw('/upload/upload_file_chunk.json', $data, 'Expect:');
  364. if ($response) {
  365. $response = json_decode($response, true);
  366. }
  367. if (!$response || $response['TotalWritten'] != $chunkStat['size']) {
  368. echo 'Unable to upload: ' . $chunk . "\n";
  369. return false;
  370. }
  371. # Remove chunks as we use them
  372. if ($tempDir) {
  373. unlink($chunk);
  374. }
  375. # Increment the offset
  376. $offset += $chunkStat['size'];
  377. unset($chunkStat);
  378. unset($response);
  379. }
  380. unset($offset);
  381. # Remove the temporary directory, if it exists
  382. if ($tempDir && is_dir($tempDir)) {
  383. rmdir($tempDir);
  384. }
  385. unset($tempDir);
  386. # Close
  387. $data = array(
  388. 'session_id' => $session,
  389. 'file_id' => $id,
  390. 'temp_location' => $tmpPath,
  391. 'file_time' => $stat['mtime'],
  392. 'file_size' => $stat['size']
  393. );
  394. $response = curlPost('/upload/close_file_upload.json', $data);
  395. # Ignore 500 errors on close. It works anyway.
  396. if ($response && !$response['DirUpdateTime']) {
  397. if ($DEBUG) {
  398. echo 'Unable to close: ' . $path . "\n";
  399. }
  400. return false;
  401. }
  402. # Return the file size on success
  403. return $stat['size'];
  404. }
  405. ?>