1
0

opendrive.php 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487
  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($response['FolderId']);
  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. # Return the ID of a file
  237. function fileID($session, $path) {
  238. $data = array(
  239. 'session_id' => $session,
  240. 'path' => $path
  241. );
  242. $response = curlPost('/file/idbypath.json', $data);
  243. # Check the result
  244. if ($response['FileId']) {
  245. return($response['FileId']);
  246. }
  247. return false;
  248. }
  249. # Return all file metadata
  250. function fileInfo($session, $path) {
  251. $id = fileID($session, $path);
  252. if (!$id) {
  253. return false;
  254. }
  255. # GET
  256. $response = curlGet('/file/info.json/' . $session . '/' . $id);
  257. # Check the result
  258. if ($response['FileId']) {
  259. return($response);
  260. }
  261. return false;
  262. }
  263. # Upload the provided file to the given path
  264. function fileUpload($session, $path, $file) {
  265. global $DEBUG;
  266. global $API_CHUNK_SIZE;
  267. # Find the local file
  268. $stat = @stat($file);
  269. if ($stat === false) {
  270. if ($DEBUG) {
  271. echo 'Unable to stat: ' . $file . "\n";
  272. }
  273. return false;
  274. }
  275. # Find the parent ID
  276. $parentID = parentID($session, $path);
  277. if ($parentID === false) {
  278. if ($DEBUG) {
  279. echo 'No parent for path: ' . $path . "\n";
  280. }
  281. return false;
  282. }
  283. # Allocate
  284. $data = array(
  285. 'session_id' => $session,
  286. 'folder_id' => $parentID,
  287. 'file_name' => basePath($path),
  288. 'file_size' => $stat['size']
  289. );
  290. $response = curlPost('/upload/create_file.json', $data);
  291. $id = $response['FileId'];
  292. if (!$id) {
  293. if ($DEBUG) {
  294. echo 'Unable to allocate: ' . $path . "\n";
  295. }
  296. return false;
  297. }
  298. # Open
  299. $data = array(
  300. 'session_id' => $session,
  301. 'file_id' => $id,
  302. 'file_size' => $stat['size']
  303. );
  304. $response = curlPost('/upload/open_file_upload.json', $data);
  305. $tmpPath = $response['TempLocation'];
  306. if (!$tmpPath) {
  307. if ($DEBUG) {
  308. echo 'Unable to open: ' . $path . "\n";
  309. }
  310. return false;
  311. }
  312. # Split if needed
  313. $tempDir = false;
  314. $files = array();
  315. if ($stat['size'] > $API_CHUNK_SIZE) {
  316. if ($DEBUG) {
  317. echo 'Splitting file: ' . $file . ' (' . $API_CHUNK_SIZE . '/' . $stat['size'] . ")\n";
  318. }
  319. # Create a temporary directory
  320. $tempDir = trim(
  321. shell_exec(
  322. 'mktemp' .
  323. ' -d' .
  324. ' --tmpdir=' . escapeshellarg(sys_get_temp_dir()) .
  325. ' ' . escapeshellarg(basename($file)) . '.XXXXXXXX'
  326. )
  327. );
  328. if (!is_dir($tempDir)) {
  329. echo "Unable to create temp directory\n";
  330. return false;
  331. }
  332. # Split into chunk-sized parts
  333. shell_exec('cd ' . escapeshellarg($tempDir) .
  334. ' && split -b ' . escapeshellarg($API_CHUNK_SIZE) . ' ' . escapeshellarg($file));
  335. # Find all their paths
  336. $fh = opendir($tempDir);
  337. if (!$fh) {
  338. echo 'Unable to open temp directory: ' . $tempDir . "\n";
  339. return false;
  340. }
  341. while (($chunk = readdir($fh)) !== false) {
  342. if (preg_match('/^x\w+$/', $chunk)) {
  343. $files[] = $tempDir . '/' . $chunk;
  344. }
  345. }
  346. unset($chunk);
  347. # Cleanup
  348. closedir($fh);
  349. unset($fh);
  350. } else {
  351. $files[] = $file;
  352. }
  353. # Sort the list to ensure the chunks are uploaded in order
  354. sort($files);
  355. # Upload
  356. $offset = 0;
  357. if (count($files) < 1) {
  358. echo 'No segments to upload: ' . $file . "\n";
  359. return false;
  360. }
  361. foreach ($files as $chunk) {
  362. if ($DEBUG > 1) {
  363. echo 'Uploading chunk: ' . $chunk . "\n";
  364. }
  365. # Find the chunk size
  366. $chunkStat = @stat($chunk);
  367. if ($chunkStat === false) {
  368. echo 'Unable to stat chunk: ' . $chunk . "\n";
  369. return false;
  370. }
  371. # Setup cURL
  372. $cfile = curl_file_create($chunk, 'application/octet-stream', basePath($file));
  373. $data = array(
  374. 'session_id' => $session,
  375. 'file_id' => $id,
  376. 'temp_location' => $tmpPath,
  377. 'chunk_offset' => $offset,
  378. 'chunk_size' => $chunkStat['size'],
  379. 'file_data' => $cfile
  380. );
  381. # Upload
  382. $response = curlPostRaw('/upload/upload_file_chunk.json', $data, 'Expect:');
  383. if ($response) {
  384. $response = json_decode($response, true);
  385. }
  386. if (!$response || $response['TotalWritten'] != $chunkStat['size']) {
  387. echo 'Unable to upload: ' . $chunk . "\n";
  388. return false;
  389. }
  390. # Remove chunks as we use them
  391. if ($tempDir) {
  392. unlink($chunk);
  393. }
  394. # Increment the offset
  395. $offset += $chunkStat['size'];
  396. unset($chunkStat);
  397. unset($response);
  398. }
  399. unset($offset);
  400. # Remove the temporary directory, if it exists
  401. if ($tempDir && is_dir($tempDir)) {
  402. rmdir($tempDir);
  403. }
  404. unset($tempDir);
  405. # Close
  406. $data = array(
  407. 'session_id' => $session,
  408. 'file_id' => $id,
  409. 'temp_location' => $tmpPath,
  410. 'file_time' => $stat['mtime'],
  411. 'file_size' => $stat['size']
  412. );
  413. $response = curlPost('/upload/close_file_upload.json', $data);
  414. if (!$response || $response['Size'] != $stat['size']) {
  415. if ($DEBUG) {
  416. echo 'Unable to close: ' . $path . "\n";
  417. }
  418. return false;
  419. }
  420. # Return the file size on success
  421. return $stat['size'];
  422. }
  423. ?>