opendrive.php 10 KB

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