opendrive.php 10 KB

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