1
0

opendrive.php 9.8 KB

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