Advertisement
Guest User

Pomf upload.php to FTP

a guest
Jan 21st, 2019
110
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 6.89 KB | None | 0 0
  1. <?php
  2.  
  3. /*****************************************/
  4. /******** CONFIGURATION VARIABLES ********/
  5. /*****************************************/
  6.  
  7. define('DATE_TIMEZONE', 'Europe/London');
  8.  
  9. define('FTP_SERVER', 'storage.bunnycdn.com');
  10. define('FTP_USER', 'username');
  11. define('FTP_PASS', 'password');
  12. define('FTP_DIR', '/dir/'); //remember trailing '/'!
  13.  
  14. /*****************************************/
  15. /****************** END ******************/
  16. /*****************************************/
  17.  
  18. header("Access-Control-Allow-Origin: *");
  19. // Check if we can compress our output; if we can, we'll do it
  20. if (ini_get('zlib.output_compression') !== 'Off'
  21. && isset($_SERVER["HTTP_ACCEPT_ENCODING"])
  22. && strpos($_SERVER["HTTP_ACCEPT_ENCODING"], 'gzip') !== false)
  23. ob_start("ob_gzhandler");
  24.  
  25. session_start();
  26. include_once 'classes/Response.class.php';
  27. include_once 'classes/UploadException.class.php';
  28. include_once 'classes/UploadedFile.class.php';
  29. include_once 'includes/database.inc.php';
  30.  
  31.  
  32. /**
  33. * Generates a random name for the file, retrying until we get an unused one
  34. *
  35. * @param UploadedFile $file
  36. * @return string
  37. */
  38. function generate_name ($file) {
  39. global $db;
  40. global $doubledots;
  41.  
  42. // We start at N retries, and --N until we give up
  43. $tries = POMF_FILES_RETRIES;
  44. $ext = pathinfo($file->name, PATHINFO_EXTENSION);
  45.  
  46. // Check if extension is a double-dot extension and, if true, override $ext
  47. $revname = strrev($file->name);
  48. foreach ($doubledots as $ddot) {
  49. if (stripos($revname, $ddot) === 0) {
  50. $ext = strrev($ddot);
  51. }
  52. }
  53.  
  54.  
  55. do {
  56. // Iterate until we reach the maximum number of retries
  57. if ($tries-- == 0) throw new Exception('Gave up trying to find an unused name', 500);
  58. if ($ext == 'exe') throw new Exception('Uploads of Windows Executable .EXE files are disabled for now', 500);
  59.  
  60. $chars = 'abcdefghijklmnopqrstuvwxyz';
  61. $name = '';
  62. for ($i = 0; $i < 6; $i++) {
  63. $name .= $chars[mt_rand(0, 25)];
  64. // $chars string length is hardcoded, should use a variable to store it?
  65. }
  66.  
  67. // Add the extension to the file name
  68. if (isset($ext) && $ext !== '')
  69. $name .= '.' . strip_tags($ext);
  70.  
  71. // Check if a file with the same name does already exist in the database
  72. $q = $db->prepare('SELECT COUNT(filename) FROM files WHERE filename = (:name)');
  73. // $q = $db->prepare('SELECT COUNT(name) FROM pomf WHERE name = (:name)');
  74. $q->bindValue(':name', $name, PDO::PARAM_STR);
  75. $q->execute();
  76. $result = $q->fetchColumn();
  77. // If it does, generate a new name
  78. } while($result > 0);
  79.  
  80. return $name;
  81. }
  82.  
  83. /**
  84. * Handles the uploading and db entry for a file
  85. *
  86. * @param UploadedFile $file
  87. * @return array
  88. */
  89. function upload_file ($file) {
  90. global $db;
  91.  
  92. // Handle file errors
  93. if ($file->error) throw new UploadException($file->error);
  94.  
  95. // Check if a file with the same hash and size (a file which is the same) does already exist in
  96. // the database; if it does, delete the file just uploaded and return the proper link and data.
  97. $q = $db->prepare('SELECT filename, COUNT(*) AS count FROM files WHERE hash = (:hash) ' .
  98. 'AND size = (:size)');
  99. $q->bindValue(':hash', $file->get_sha1(), PDO::PARAM_STR);
  100. $q->bindValue(':size', $file->size, PDO::PARAM_INT);
  101. $q->execute();
  102. $result = $q->fetch();
  103. if ($result['count'] > 0) {
  104. unlink($file->tempfile);
  105. return array(
  106. 'hash' => $file->get_sha1(),
  107. 'name' => $file->name,
  108. 'url' => POMF_URL . $result['filename'],
  109. 'size' => $file->size
  110. );
  111. }
  112.  
  113. // Generate a name for the file
  114. $newname = generate_name($file);
  115.  
  116. // upload to CDN
  117. $ftpconn = ftp_connect(FTP_SERVER);
  118. if($ftpconn != FALSE){
  119. ftp_pasv($ftpconn, true);
  120.  
  121. if(ftp_login($ftpconn, FTP_USER, FTP_PASS)){
  122. if(ftp_put($ftpconn, FTP_DIR.$newname, $file->tempfile, FTP_BINARY)){
  123. ftp_close($ftpconn);
  124. // Add it to the database
  125. if (empty($_SESSION['id'])) {
  126. // Query if user is NOT logged in
  127. $q = $db->prepare('INSERT INTO files (hash, originalname, filename, size, date, ' .
  128. 'expire, delid) VALUES (:hash, :orig, :name, :size, :date, ' .
  129. ':exp, :del)');
  130. } else {
  131. // Query if user is logged in (insert user id together with other data)
  132. $q = $db->prepare('INSERT INTO files (hash, originalname, filename, size, date, ' .
  133. 'expire, delid, user) VALUES (:hash, :orig, :name, :size, ' .
  134. ':date, :expires, :delid, :user)');
  135. $q->bindValue(':user', $_SESSION['id'], PDO::PARAM_INT);
  136. }
  137.  
  138. // Common parameters binding
  139. date_default_timezone_set(DATE_TIMEZONE);
  140. $q->bindValue(':hash', $file->get_sha1(), PDO::PARAM_STR);
  141. $q->bindValue(':orig', strip_tags($file->name), PDO::PARAM_STR);
  142. $q->bindValue(':name', $newname, PDO::PARAM_STR);
  143. $q->bindValue(':size', $file->size, PDO::PARAM_INT);
  144. $q->bindValue(':date', date('Y-m-d'), PDO::PARAM_STR);
  145. $q->bindValue(':exp', null, PDO::PARAM_STR);
  146. $q->bindValue(':del', sha1($file->tempfile), PDO::PARAM_STR);
  147. $q->execute();
  148.  
  149. return array(
  150. 'hash' => $file->get_sha1(),
  151. 'name' => $file->name,
  152. 'url' => POMF_URL . $newname,
  153. 'size' => $file->size
  154. );
  155. } else {
  156. ftp_close($ftpconn);
  157. throw new Exception('Failed to upload to FTP', 500);
  158. }
  159. } else {
  160. ftp_close($ftpconn);
  161. throw new Exception('Failed to log in to FTP', 500);
  162. }
  163. } else {
  164. throw new Exception('Failed to connect to FTP', 500);
  165. }
  166. }
  167.  
  168. /**
  169. * Reorder files array by file
  170. *
  171. * @param $_FILES
  172. * @return array
  173. */
  174. function diverse_array ($files) {
  175. $result = array();
  176. foreach ($files as $key1 => $value1)
  177. foreach ($value1 as $key2 => $value2)
  178. $result[$key2][$key1] = $value2;
  179.  
  180. return $result;
  181. }
  182.  
  183. /**
  184. * Reorganize the $_FILES array into something saner
  185. *
  186. * @param $_FILES
  187. * @return array
  188. */
  189. function refiles ($files) {
  190. $result = array();
  191. $files = diverse_array($files);
  192.  
  193. foreach ($files as $file) {
  194. $f = new UploadedFile();
  195. $f->name = $file['name'];
  196. $f->mime = $file['type'];
  197. $f->size = $file['size'];
  198. $f->tempfile = $file['tmp_name'];
  199. $f->error = $file['error'];
  200. // 'expire' doesn't exist neither in $_FILES nor in UploadedFile;
  201. // commented out for future implementation
  202. //$f->expire = $file['expire'];
  203. $result[] = $f;
  204. }
  205.  
  206. return $result;
  207. }
  208.  
  209.  
  210.  
  211. $type = isset($_GET['output']) ? $_GET['output'] : 'json';
  212. $response = new Response($type);
  213. if (isset($_FILES['files'])) {
  214. $uploads = refiles($_FILES['files']);
  215. try {
  216. foreach ($uploads as $upload)
  217. $res[] = upload_file($upload);
  218. $response->send($res);
  219. } catch (Exception $e) {
  220. $response->error($e->getCode(), $e->getMessage());
  221. }
  222. } else {
  223. $response->error(400, 'No input file(s)');
  224. }
  225.  
  226. ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement