PageRenderTime 26ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 0ms

/ext/upload/main.php

https://gitlab.com/dali99/shimmie2-Material-Theme
PHP | 430 lines | 295 code | 51 blank | 84 comment | 68 complexity | 3929c18fe144e4be3d8aed106944da44 MD5 | raw file
  1. <?php
  2. /**
  3. * Name: Uploader
  4. * Author: Shish <webmaster@shishnet.org>
  5. * Link: http://code.shishnet.org/shimmie2/
  6. * Description: Allows people to upload files to the website
  7. */
  8. /**
  9. * Occurs when some data is being uploaded.
  10. */
  11. class DataUploadEvent extends Event {
  12. /** @var string */
  13. public $tmpname;
  14. /** @var array */
  15. public $metadata;
  16. /** @var string */
  17. public $hash;
  18. /** @var string */
  19. public $type;
  20. /** @var int */
  21. public $image_id = -1;
  22. /**
  23. * Some data is being uploaded.
  24. * This should be caught by a file handler.
  25. * -- Removed: param $user The user uploading the data.
  26. * @param string $tmpname The temporary file used for upload.
  27. * @param array $metadata Info about the file, should contain at least "filename", "extension", "tags" and "source".
  28. */
  29. public function __construct(/*string*/ $tmpname, /*array*/ $metadata) {
  30. assert(file_exists($tmpname));
  31. $this->tmpname = $tmpname;
  32. $this->metadata = $metadata;
  33. $this->metadata['hash'] = md5_file($tmpname);
  34. $this->metadata['size'] = filesize($tmpname);
  35. // useful for most file handlers, so pull directly into fields
  36. $this->hash = $this->metadata['hash'];
  37. $this->type = strtolower($metadata['extension']);
  38. }
  39. }
  40. class UploadException extends SCoreException {}
  41. /**
  42. * Main upload class.
  43. * All files that are uploaded to the site are handled through this class.
  44. * This also includes transloaded files as well.
  45. */
  46. class Upload extends Extension {
  47. /** @var bool */
  48. public $is_full;
  49. /**
  50. * Early, so it can stop the DataUploadEvent before any data handlers see it.
  51. *
  52. * @return int
  53. */
  54. public function get_priority() {return 40;}
  55. public function onInitExt(InitExtEvent $event) {
  56. global $config;
  57. $config->set_default_int('upload_count', 3);
  58. $config->set_default_int('upload_size', '1MB');
  59. $config->set_default_int('upload_min_free_space', '100MB');
  60. $config->set_default_bool('upload_tlsource', TRUE);
  61. $this->is_full = false;
  62. $min_free_space = $config->get_int("upload_min_free_space");
  63. if($min_free_space > 0) {
  64. // SHIT: fucking PHP "security" measures -_-;;;
  65. $free_num = @disk_free_space(realpath("./images/"));
  66. if($free_num !== FALSE) {
  67. $this->is_full = $free_num < $min_free_space;
  68. }
  69. }
  70. }
  71. public function onPostListBuilding(PostListBuildingEvent $event) {
  72. global $user, $page;
  73. if($user->can("create_image")) {
  74. if($this->is_full) {
  75. $this->theme->display_full($page);
  76. }
  77. else {
  78. $this->theme->display_block($page);
  79. }
  80. }
  81. }
  82. public function onSetupBuilding(SetupBuildingEvent $event) {
  83. $tes = array();
  84. $tes["Disabled"] = "none";
  85. if(function_exists("curl_init")) {
  86. $tes["cURL"] = "curl";
  87. }
  88. $tes["fopen"] = "fopen";
  89. $tes["WGet"] = "wget";
  90. $sb = new SetupBlock("Upload");
  91. $sb->position = 10;
  92. // Output the limits from PHP so the user has an idea of what they can set.
  93. $sb->add_int_option("upload_count", "Max uploads: ");
  94. $sb->add_label("<i>PHP Limit = ".ini_get('max_file_uploads')."</i>");
  95. $sb->add_shorthand_int_option("upload_size", "<br/>Max size per file: ");
  96. $sb->add_label("<i>PHP Limit = ".ini_get('upload_max_filesize')."</i>");
  97. $sb->add_choice_option("transload_engine", $tes, "<br/>Transload: ");
  98. $sb->add_bool_option("upload_tlsource", "<br/>Use transloaded URL as source if none is provided: ");
  99. $event->panel->add_block($sb);
  100. }
  101. public function onDataUpload(DataUploadEvent $event) {
  102. global $config;
  103. if($this->is_full) {
  104. throw new UploadException("Upload failed; disk nearly full");
  105. }
  106. if(filesize($event->tmpname) > $config->get_int('upload_size')) {
  107. $size = to_shorthand_int(filesize($event->tmpname));
  108. $limit = to_shorthand_int($config->get_int('upload_size'));
  109. throw new UploadException("File too large ($size &gt; $limit)");
  110. }
  111. }
  112. public function onPageRequest(PageRequestEvent $event) {
  113. global $page, $user;
  114. if($event->page_matches("upload/replace")) {
  115. // check if the user is an administrator and can upload files.
  116. if(!$user->can("replace_image")) {
  117. $this->theme->display_permission_denied();
  118. }
  119. else {
  120. if($this->is_full) {
  121. throw new UploadException("Can not replace Image: disk nearly full");
  122. }
  123. // Try to get the image ID
  124. $image_id = int_escape($event->get_arg(0));
  125. if(empty($image_id)) {
  126. $image_id = isset($_POST['image_id']) ? $_POST['image_id'] : null;
  127. }
  128. if(empty($image_id)) {
  129. throw new UploadException("Can not replace Image: No valid Image ID given.");
  130. }
  131. $image_old = Image::by_id($image_id);
  132. if(is_null($image_old)) {
  133. $this->theme->display_error(404, "Image not found", "No image in the database has the ID #$image_id");
  134. }
  135. if(count($_FILES) + count($_POST) > 0) {
  136. if(count($_FILES) > 1) {
  137. throw new UploadException("Can not upload more than one image for replacing.");
  138. }
  139. $source = isset($_POST['source']) ? $_POST['source'] : null;
  140. $tags = ''; // Tags aren't changed when uploading. Set to null to stop PHP warnings.
  141. $ok = false;
  142. if(count($_FILES)) {
  143. foreach($_FILES as $file) {
  144. $ok = $this->try_upload($file, $tags, $source, $image_id);
  145. break; // leave the foreach loop.
  146. }
  147. }
  148. else {
  149. foreach($_POST as $name => $value) {
  150. if(substr($name, 0, 3) == "url" && strlen($value) > 0) {
  151. $ok = $this->try_transload($value, $tags, $source, $image_id);
  152. break; // leave the foreach loop.
  153. }
  154. }
  155. }
  156. $this->theme->display_upload_status($page, $ok);
  157. }
  158. else if(!empty($_GET['url'])) {
  159. $url = $_GET['url'];
  160. $tags = isset($_GET['tags']) ? $_GET['tags'] : 'tagme';
  161. $source = isset($_GET['source']) ? $_GET['source'] : $url;
  162. $ok = $this->try_transload($url, $tags, $source, $image_id);
  163. $this->theme->display_upload_status($page, $ok);
  164. }
  165. else {
  166. $this->theme->display_replace_page($page, $image_id);
  167. }
  168. }
  169. }
  170. else if($event->page_matches("upload")) {
  171. if(!$user->can("create_image")) {
  172. $this->theme->display_permission_denied();
  173. }
  174. else {
  175. /* Regular Upload Image */
  176. if(count($_FILES) + count($_POST) > 0) {
  177. $ok = true;
  178. foreach($_FILES as $name => $file) {
  179. $tags = $this->tags_for_upload_slot(int_escape(substr($name, 4)));
  180. $source = isset($_POST['source']) ? $_POST['source'] : null;
  181. $ok = $ok & $this->try_upload($file, $tags, $source);
  182. }
  183. foreach($_POST as $name => $value) {
  184. if(substr($name, 0, 3) == "url" && strlen($value) > 0) {
  185. $tags = $this->tags_for_upload_slot(int_escape(substr($name, 3)));
  186. $source = isset($_POST['source']) ? $_POST['source'] : $value;
  187. $ok = $ok & $this->try_transload($value, $tags, $source);
  188. }
  189. }
  190. $this->theme->display_upload_status($page, $ok);
  191. }
  192. else if(!empty($_GET['url'])) {
  193. $url = $_GET['url'];
  194. $source = isset($_GET['source']) ? $_GET['source'] : $url;
  195. $tags = array('tagme');
  196. if(!empty($_GET['tags']) && $_GET['tags'] != "null") {
  197. $tags = Tag::explode($_GET['tags']);
  198. }
  199. $ok = $this->try_transload($url, $tags, $source);
  200. $this->theme->display_upload_status($page, $ok);
  201. }
  202. else {
  203. if ($this->is_full) {
  204. $this->theme->display_full($page);
  205. } else {
  206. $this->theme->display_page($page);
  207. }
  208. }
  209. }
  210. }
  211. }
  212. /**
  213. * @param int $id
  214. * @return string[]
  215. */
  216. private function tags_for_upload_slot($id) {
  217. if(isset($_POST["tags$id"])) {
  218. # merge then explode, not explode then merge - else
  219. # one of the merges may create a surplus "tagme"
  220. $tags = Tag::explode($_POST['tags'] . " " . $_POST["tags$id"]);
  221. }
  222. else {
  223. $tags = Tag::explode($_POST['tags']);
  224. }
  225. return $tags;
  226. }
  227. // do things {{{
  228. /**
  229. * Returns a descriptive error message for the specified PHP error code.
  230. *
  231. * This is a helper function based on the one from the online PHP Documentation
  232. * which is licensed under Creative Commons Attribution 3.0 License
  233. *
  234. * TODO: Make these messages user/admin editable
  235. *
  236. * @param int $error_code PHP error code
  237. * @return string
  238. */
  239. private function upload_error_message($error_code) {
  240. switch ($error_code) {
  241. case UPLOAD_ERR_INI_SIZE:
  242. return 'The uploaded file exceeds the upload_max_filesize directive in php.ini';
  243. case UPLOAD_ERR_FORM_SIZE:
  244. return 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form';
  245. case UPLOAD_ERR_PARTIAL:
  246. return 'The uploaded file was only partially uploaded';
  247. case UPLOAD_ERR_NO_FILE:
  248. return 'No file was uploaded';
  249. case UPLOAD_ERR_NO_TMP_DIR:
  250. return 'Missing a temporary folder';
  251. case UPLOAD_ERR_CANT_WRITE:
  252. return 'Failed to write file to disk';
  253. case UPLOAD_ERR_EXTENSION:
  254. return 'File upload stopped by extension';
  255. default:
  256. return 'Unknown upload error';
  257. }
  258. }
  259. /**
  260. * Handle an upload.
  261. * @param $file
  262. * @param $tags
  263. * @param $source
  264. * @param string $replace
  265. * @return bool TRUE on upload successful.
  266. */
  267. private function try_upload($file, $tags, $source, $replace='') {
  268. global $page;
  269. if(empty($source)) $source = null;
  270. $ok = true;
  271. // blank file boxes cause empty uploads, no need for error message
  272. if (!empty($file['name'])) {
  273. try {
  274. // check if the upload was successful
  275. if ($file['error'] !== UPLOAD_ERR_OK) {
  276. throw new UploadException($this->upload_error_message($file['error']));
  277. }
  278. $pathinfo = pathinfo($file['name']);
  279. $metadata = array();
  280. $metadata['filename'] = $pathinfo['basename'];
  281. $metadata['extension'] = $pathinfo['extension'];
  282. $metadata['tags'] = $tags;
  283. $metadata['source'] = $source;
  284. /* check if we have been given an image ID to replace */
  285. if (!empty($replace)) {
  286. $metadata['replace'] = $replace;
  287. }
  288. $event = new DataUploadEvent($file['tmp_name'], $metadata);
  289. send_event($event);
  290. if($event->image_id == -1) {
  291. throw new UploadException("File type not recognised");
  292. }
  293. $page->add_http_header("X-Shimmie-Image-ID: ".int_escape($event->image_id));
  294. }
  295. catch(UploadException $ex) {
  296. $this->theme->display_upload_error($page, "Error with ".html_escape($file['name']),
  297. $ex->getMessage());
  298. $ok = false;
  299. }
  300. }
  301. return $ok;
  302. }
  303. /**
  304. * Handle an transload.
  305. *
  306. * @param string $url
  307. * @param mixed $tags
  308. * @param string $source
  309. * @param string $replace
  310. * @return bool Returns TRUE on transload successful.
  311. */
  312. private function try_transload($url, $tags, $source, $replace='') {
  313. global $page, $config, $user;
  314. $ok = true;
  315. // Checks if user is admin > check if you want locked.
  316. if($user->can("edit_image_lock") && !empty($_GET['locked'])){
  317. $locked = bool_escape($_GET['locked']);
  318. }
  319. // Checks if url contains rating, also checks if the rating extension is enabled.
  320. if($config->get_string("transload_engine", "none") != "none" && ext_is_live("Ratings") && !empty($_GET['rating'])) {
  321. // Rating event will validate that this is s/q/e/u
  322. $rating = strtolower($_GET['rating']);
  323. $rating = $rating[0];
  324. }else{
  325. $rating = "";
  326. }
  327. $tmp_filename = tempnam(ini_get('upload_tmp_dir'), "shimmie_transload");
  328. // transload() returns Array or Bool, depending on the transload_engine.
  329. $headers = transload($url, $tmp_filename);
  330. $s_filename = is_array($headers) ? findHeader($headers, 'Content-Disposition') : null;
  331. $h_filename = ($s_filename ? preg_replace('/^.*filename="([^ ]+)"/i', '$1', $s_filename) : null);
  332. $filename = $h_filename ?: basename($url);
  333. if(!$headers) {
  334. $this->theme->display_upload_error($page, "Error with ".html_escape($filename),
  335. "Error reading from ".html_escape($url));
  336. return false;
  337. }
  338. if(filesize($tmp_filename) == 0) {
  339. $this->theme->display_upload_error($page, "Error with ".html_escape($filename),
  340. "No data found -- perhaps the site has hotlink protection?");
  341. $ok = false;
  342. }else{
  343. $pathinfo = pathinfo($url);
  344. $metadata = array();
  345. $metadata['filename'] = $filename;
  346. $metadata['tags'] = $tags;
  347. $metadata['source'] = (($url == $source) && !$config->get_bool('upload_tlsource') ? "" : $source);
  348. if (is_array($headers)) {
  349. $metadata['extension'] = getExtension(findHeader($headers, 'Content-Type'));
  350. } else {
  351. $metadata['extension'] = $pathinfo['extension'];
  352. }
  353. /* check for locked > adds to metadata if it has */
  354. if(!empty($locked)){
  355. $metadata['locked'] = $locked ? "on" : "";
  356. }
  357. /* check for rating > adds to metadata if it has */
  358. if(!empty($rating)){
  359. $metadata['rating'] = $rating;
  360. }
  361. /* check if we have been given an image ID to replace */
  362. if (!empty($replace)) {
  363. $metadata['replace'] = $replace;
  364. }
  365. $event = new DataUploadEvent($tmp_filename, $metadata);
  366. try {
  367. send_event($event);
  368. }
  369. catch(UploadException $ex) {
  370. $this->theme->display_upload_error($page, "Error with ".html_escape($url),
  371. $ex->getMessage());
  372. $ok = false;
  373. }
  374. }
  375. unlink($tmp_filename);
  376. return $ok;
  377. }
  378. // }}}
  379. }