opendrive.php 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463
  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:\n";
  88. print_r($response);
  89. }
  90. return($response);
  91. }
  92. # POST the provided data to OpenDrive
  93. function curlPost($url, $data) {
  94. $data = json_encode($data);
  95. $response = curlPostRaw($url, $data, 'Content-Type: application/json');
  96. $responseData = json_decode($response, true);
  97. if ($DEBUG >= 3) {
  98. echo "Response Data:\n";
  99. print_r($responseData);
  100. }
  101. return($responseData);
  102. }
  103. # GET from OpenDrive
  104. function curlGet($url) {
  105. global $API_BASE;
  106. global $CA_PATH;
  107. global $DEBUG;
  108. # Setup cURL
  109. $ch = curl_init($API_BASE . $url);
  110. curl_setopt_array($ch, array(
  111. CURLOPT_CAINFO => $CA_PATH,
  112. CURLOPT_RETURNTRANSFER => true
  113. ));
  114. if ($DEBUG >= 3) {
  115. curl_setopt($ch, CURLOPT_VERBOSE, true);
  116. }
  117. # Send the request
  118. if ($DEBUG >= 2) {
  119. echo 'Request: ' . $url . "\n";
  120. print_r($data);
  121. echo "\n";
  122. }
  123. $response = curl_exec($ch);
  124. # Check for errors
  125. if ($response === FALSE){
  126. die(curl_error($ch));
  127. }
  128. # Return
  129. $responseData = json_decode($response, true);
  130. return($responseData);
  131. }
  132. # Login to OD and return the SessionID
  133. function login() {
  134. global $API_VERSION;
  135. global $OD_USER;
  136. global $OD_PASSWD;
  137. $data = array(
  138. 'username' => $OD_USER,
  139. 'passwd' => $OD_PASSWD,
  140. 'version' => $API_VERSION
  141. );
  142. $response = curlPost('/session/login.json', $data);
  143. # Check the result
  144. if ($response['SessionID']) {
  145. return $response['SessionID'];
  146. }
  147. return false;
  148. }
  149. # Logout of OpenDrive
  150. function logout($session) {
  151. $data = array(
  152. 'session_id' => $session
  153. );
  154. $response = curlPost('/session/logout.json', $data);
  155. # Check the result
  156. if ($response['result'] == 'true') {
  157. return true;
  158. }
  159. return false;
  160. }
  161. # Return the ID of a folder
  162. function folderID($session, $path) {
  163. $data = array(
  164. 'session_id' => $session,
  165. 'path' => $path
  166. );
  167. $response = curlPost('/folder/idbypath.json', $data);
  168. # Check the result
  169. if ($response['FolderId']) {
  170. return($response['FolderId']);
  171. }
  172. return false;
  173. }
  174. # Find the parent ID for a given path
  175. function parentID($session, $path) {
  176. $parent = parentPath($path);
  177. $parentID = 0;
  178. if ($parent != '.') {
  179. $parentID = folderID($session, $parent);
  180. }
  181. return $parentID;
  182. }
  183. # Create a folder
  184. function mkFolder($session, $path) {
  185. global $DEBUG;
  186. # Find the parent ID (if any)
  187. $parentID = parentID($session, $path);
  188. if ($parentID === false) {
  189. if ($DEBUG) {
  190. echo 'Invalid parent for path: ' . $path . "\n";
  191. }
  192. return false;
  193. }
  194. # POST
  195. $data = array(
  196. 'session_id' => $session,
  197. 'folder_name' => basePath($path),
  198. 'folder_sub_parent' => $parentID,
  199. 'folder_is_public' => 0
  200. );
  201. $response = curlPost('/folder.json', $data);
  202. # Check the result
  203. if ($response['FolderId']) {
  204. return($response['FolderId']);
  205. }
  206. return false;
  207. }
  208. # Trash a folder
  209. function rmFolder($session, $path) {
  210. $id = folderID($session, $path);
  211. if (!$id) {
  212. return false;
  213. }
  214. $data = array(
  215. 'session_id' => $session,
  216. 'folder_id' => $id
  217. );
  218. $response = curlPost('/folder/trash.json', $data);
  219. # Check the result
  220. if ($response['DirUpdateTime']) {
  221. return true;
  222. }
  223. return false;
  224. }
  225. # Return the ID of a file
  226. function fileID($session, $path) {
  227. $data = array(
  228. 'session_id' => $session,
  229. 'path' => $path
  230. );
  231. $response = curlPost('/file/idbypath.json', $data);
  232. # Check the result
  233. if ($response['FileId']) {
  234. return($response['FileId']);
  235. }
  236. return false;
  237. }
  238. # Return all file metadata
  239. function fileInfo($session, $path) {
  240. $id = fileID($session, $path);
  241. if (!$id) {
  242. return false;
  243. }
  244. # GET
  245. $response = curlGet('/file/info.json/' . $session . '/' . $id);
  246. # Check the result
  247. if ($response['FileId']) {
  248. return($response);
  249. }
  250. return false;
  251. }
  252. # Upload the provided file to the given path
  253. function fileUpload($session, $path, $file) {
  254. global $DEBUG;
  255. global $API_CHUNK_SIZE;
  256. # Find the local file
  257. $stat = @stat($file);
  258. if ($stat === false) {
  259. if ($DEBUG) {
  260. echo 'Unable to stat: ' . $file . "\n";
  261. }
  262. return false;
  263. }
  264. # Find the parent ID
  265. $parentID = parentID($session, $path);
  266. if ($parentID === false) {
  267. if ($DEBUG) {
  268. echo 'No parent for path: ' . $path . "\n";
  269. }
  270. return false;
  271. }
  272. # Allocate
  273. $data = array(
  274. 'session_id' => $session,
  275. 'folder_id' => $parentID,
  276. 'file_name' => basePath($path),
  277. 'file_size' => $stat['size']
  278. );
  279. $response = curlPost('/upload/create_file.json', $data);
  280. $id = $response['FileId'];
  281. if (!$id) {
  282. if ($DEBUG) {
  283. echo 'Unable to allocate: ' . $path . "\n";
  284. }
  285. return false;
  286. }
  287. # Open
  288. $data = array(
  289. 'session_id' => $session,
  290. 'file_id' => $id,
  291. 'file_size' => $stat['size']
  292. );
  293. $response = curlPost('/upload/open_file_upload.json', $data);
  294. $tmpPath = $response['TempLocation'];
  295. if (!$tmpPath) {
  296. if ($DEBUG) {
  297. echo 'Unable to open: ' . $path . "\n";
  298. }
  299. return false;
  300. }
  301. # Split if needed
  302. $tempDir = false;
  303. $files = array();
  304. if ($stat['size'] > $API_CHUNK_SIZE) {
  305. if ($DEBUG) {
  306. echo 'Splitting file: ' . $file . ' (' . $API_CHUNK_SIZE . '/' . $stat['size'] . ")\n";
  307. }
  308. # Create a temporary directory
  309. $tempDir = trim(shell_exec('mktemp -d'));
  310. if (!is_dir($tempDir)) {
  311. echo "Unable to create temp directory\n";
  312. return false;
  313. }
  314. # Split into chunk-sized parts
  315. shell_exec('cd ' . escapeshellarg($tempDir) .
  316. ' && split -b ' . escapeshellarg($API_CHUNK_SIZE) . ' ' . escapeshellarg($file));
  317. # Find all their paths
  318. $fh = opendir($tempDir);
  319. if (!$fh) {
  320. echo 'Unable to open temp directory: ' . $tempDir . "\n";
  321. return false;
  322. }
  323. while (($chunk = readdir($fh)) !== false) {
  324. if (preg_match('/^x\w+$/', $chunk)) {
  325. $files[] = $tempDir . '/' . $chunk;
  326. }
  327. }
  328. unset($chunk);
  329. # Cleanup
  330. closedir($fh);
  331. unset($fh);
  332. } else {
  333. $files[] = $file;
  334. }
  335. # Sort the list to ensure the chunks are uploaded in order
  336. sort($files);
  337. # Upload
  338. $offset = 0;
  339. foreach ($files as $chunk) {
  340. if ($DEBUG > 1) {
  341. echo 'Uploading chunk: ' . $chunk . "\n";
  342. }
  343. # Find the chunk size
  344. $chunkStat = @stat($chunk);
  345. if ($chunkStat === false) {
  346. echo 'Unable to stat chunk: ' . $chunk . "\n";
  347. return false;
  348. }
  349. # Setup cURL
  350. $cfile = curl_file_create($chunk, 'application/octet-stream', basePath($file));
  351. $data = array(
  352. 'session_id' => $session,
  353. 'file_id' => $id,
  354. 'temp_location' => $tmpPath,
  355. 'chunk_offset' => $offset,
  356. 'chunk_size' => $chunkStat['size'],
  357. 'file_data' => $cfile
  358. );
  359. # Upload
  360. $response = curlPostRaw('/upload/upload_file_chunk.json', $data, 'Expect:');
  361. if ($response) {
  362. $response = json_decode($response, true);
  363. }
  364. if (!$response || $response['TotalWritten'] != $chunkStat['size']) {
  365. echo 'Unable to upload: ' . $chunk . "\n";
  366. return false;
  367. }
  368. # Remove chunks as we use them
  369. if ($tempDir) {
  370. unlink($chunk);
  371. }
  372. # Increment the offset
  373. $offset += $chunkStat['size'];
  374. unset($chunkStat);
  375. unset($response);
  376. }
  377. unset($offset);
  378. # Remove the temporary directory, if it exists
  379. if ($tempDir && is_dir($tempDir)) {
  380. rmdir($tempDir);
  381. }
  382. unset($tempDir);
  383. # Close
  384. $data = array(
  385. 'session_id' => $session,
  386. 'file_id' => $id,
  387. 'temp_location' => $tmpPath,
  388. 'file_time' => $stat['mtime'],
  389. 'file_size' => $stat['size']
  390. );
  391. $response = curlPost('/upload/close_file_upload.json', $data);
  392. # Ignore 500 errors on close. It works anyway.
  393. if ($response && !$response['DirUpdateTime']) {
  394. if ($DEBUG) {
  395. echo 'Unable to close: ' . $path . "\n";
  396. }
  397. return false;
  398. }
  399. # Return the file size on success
  400. return $stat['size'];
  401. }
  402. ?>