class-qdr-tss-upload-controller.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389
  1. <?php
  2. /**
  3. * Upload REST API Controller for the plugin.
  4. *
  5. * This class handles REST API endpoints for file upload operations.
  6. *
  7. * @package QDR_Temporary_Shared_Storage
  8. * @since 1.0.0
  9. */
  10. class QDR_TSS_Upload_Controller {
  11. /**
  12. * The plugin name.
  13. *
  14. * @since 1.0.0
  15. * @access private
  16. * @var string $plugin_name The name of this plugin.
  17. */
  18. private $plugin_name;
  19. /**
  20. * The plugin version.
  21. *
  22. * @since 1.0.0
  23. * @access private
  24. * @var string $version The version of this plugin.
  25. */
  26. private $version;
  27. /**
  28. * The namespace for the REST API routes.
  29. *
  30. * @since 1.0.0
  31. * @access private
  32. * @var string $namespace The namespace for the REST API routes.
  33. */
  34. private $namespace = 'qdr-tss/v1';
  35. /**
  36. * The database manager instance.
  37. *
  38. * @since 1.0.0
  39. * @access private
  40. * @var QDR_TSS_DB_Manager $db_manager The database manager instance.
  41. */
  42. private $db_manager;
  43. /**
  44. * The file manager instance.
  45. *
  46. * @since 1.0.0
  47. * @access private
  48. * @var QDR_TSS_File_Manager $file_manager The file manager instance.
  49. */
  50. private $file_manager;
  51. /**
  52. * The settings instance.
  53. *
  54. * @since 1.0.0
  55. * @access private
  56. * @var QDR_TSS_Settings $settings The settings instance.
  57. */
  58. private $settings;
  59. /**
  60. * Initialize the class and set its properties.
  61. *
  62. * @since 1.0.0
  63. * @param string $plugin_name The name of this plugin.
  64. * @param string $version The version of this plugin.
  65. */
  66. public function __construct($plugin_name, $version) {
  67. $this->plugin_name = $plugin_name;
  68. $this->version = $version;
  69. $this->db_manager = QDR_TSS_DB_Manager::instance();
  70. $this->file_manager = QDR_TSS_File_Manager::instance();
  71. $this->settings = QDR_TSS_Settings::instance();
  72. }
  73. /**
  74. * Register the REST API routes.
  75. *
  76. * @since 1.0.0
  77. */
  78. public function register_routes() {
  79. // Chunked upload endpoints
  80. register_rest_route($this->namespace, '/upload/init', array(
  81. 'methods' => WP_REST_Server::CREATABLE,
  82. 'callback' => array($this, 'init_chunked_upload'),
  83. 'permission_callback' => array($this, 'check_permission'),
  84. ));
  85. register_rest_route($this->namespace, '/upload/chunk', array(
  86. 'methods' => WP_REST_Server::CREATABLE,
  87. 'callback' => array($this, 'upload_chunk'),
  88. 'permission_callback' => array($this, 'check_permission'),
  89. ));
  90. register_rest_route($this->namespace, '/upload/finalize', array(
  91. 'methods' => WP_REST_Server::CREATABLE,
  92. 'callback' => array($this, 'finalize_chunked_upload'),
  93. 'permission_callback' => array($this, 'check_permission'),
  94. ));
  95. }
  96. /**
  97. * Check permission for REST API requests.
  98. *
  99. * @since 1.0.0
  100. * @return bool True if authorized, false otherwise.
  101. */
  102. public function check_permission() {
  103. $rest_controller = new QDR_TSS_REST_Controller($this->plugin_name, $this->version);
  104. return $rest_controller->check_rest_permission();
  105. }
  106. /**
  107. * Initialize chunked upload.
  108. *
  109. * @since 1.0.0
  110. * @param WP_REST_Request $request Full details about the request.
  111. * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure.
  112. */
  113. public function init_chunked_upload($request) {
  114. // Check required parameters
  115. if (!isset($request['original_file_name']) || !isset($request['file_size'])) {
  116. return new WP_Error(
  117. 'qdr_tss_missing_params',
  118. __('Missing required parameters.', 'qdr-temporary-shared-storage'),
  119. array('status' => 400)
  120. );
  121. }
  122. $file_size = (int) $request['file_size'];
  123. $max_upload_size = $this->settings->get_setting('max_upload_size');
  124. // Check max upload size
  125. if ($file_size > $max_upload_size) {
  126. return new WP_Error(
  127. 'qdr_tss_file_too_large',
  128. __('File exceeds maximum upload size.', 'qdr-temporary-shared-storage'),
  129. array('status' => 400)
  130. );
  131. }
  132. // Check total storage usage
  133. if ($this->db_manager->would_exceed_storage_limit($file_size, $max_upload_size)) {
  134. return new WP_Error(
  135. 'qdr_tss_storage_limit',
  136. __('Storage limit exceeded.', 'qdr-temporary-shared-storage'),
  137. array('status' => 400)
  138. );
  139. }
  140. // Initialize chunked upload
  141. $upload_id = $this->file_manager->init_chunked_upload();
  142. if (!$upload_id) {
  143. return new WP_Error(
  144. 'qdr_tss_init_failed',
  145. __('Failed to initialize upload.', 'qdr-temporary-shared-storage'),
  146. array('status' => 500)
  147. );
  148. }
  149. return new WP_REST_Response(array(
  150. 'upload_id' => $upload_id,
  151. 'status' => 'initialized'
  152. ), 200);
  153. }
  154. /**
  155. * Upload a chunk.
  156. *
  157. * @since 1.0.0
  158. * @param WP_REST_Request $request Full details about the request.
  159. * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure.
  160. */
  161. public function upload_chunk($request) {
  162. // Check required parameters
  163. if (!isset($request['upload_id']) || !isset($request['chunk_index']) || !isset($request['total_chunks'])) {
  164. return new WP_Error(
  165. 'qdr_tss_missing_params',
  166. __('Missing required parameters.', 'qdr-temporary-shared-storage'),
  167. array('status' => 400)
  168. );
  169. }
  170. $upload_id = $request['upload_id'];
  171. $chunk_index = (int) $request['chunk_index'];
  172. $total_chunks = (int) $request['total_chunks'];
  173. // Handle file upload
  174. $files = $request->get_file_params();
  175. if (empty($files) || !isset($files['chunk'])) {
  176. return new WP_Error(
  177. 'qdr_tss_no_file',
  178. __('No file uploaded.', 'qdr-temporary-shared-storage'),
  179. array('status' => 400)
  180. );
  181. }
  182. $chunk_file = $files['chunk'];
  183. // Store chunk
  184. $result = $this->file_manager->store_chunk($upload_id, $chunk_index, $chunk_file);
  185. if (!$result) {
  186. return new WP_Error(
  187. 'qdr_tss_chunk_failed',
  188. __('Failed to upload chunk.', 'qdr-temporary-shared-storage'),
  189. array('status' => 500)
  190. );
  191. }
  192. return new WP_REST_Response(array(
  193. 'upload_id' => $upload_id,
  194. 'chunk_index' => $chunk_index,
  195. 'status' => 'chunk_uploaded'
  196. ), 200);
  197. }
  198. /**
  199. * Finalize chunked upload.
  200. *
  201. * @since 1.0.0
  202. * @param WP_REST_Request $request Full details about the request.
  203. * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure.
  204. */
  205. public function finalize_chunked_upload($request) {
  206. // Check required parameters
  207. if (!isset($request['upload_id']) || !isset($request['total_chunks'])) {
  208. return new WP_Error(
  209. 'qdr_tss_missing_params',
  210. __('Missing required parameters.', 'qdr-temporary-shared-storage'),
  211. array('status' => 400)
  212. );
  213. }
  214. $upload_id = $request['upload_id'];
  215. $total_chunks = (int) $request['total_chunks'];
  216. // Check for required file metadata
  217. $required_fields = array('original_file_name', 'description', 'password');
  218. foreach ($required_fields as $field) {
  219. if (!isset($request[$field]) || empty($request[$field])) {
  220. return new WP_Error(
  221. 'qdr_tss_missing_field',
  222. sprintf(__('Missing required field: %s', 'qdr-temporary-shared-storage'), $field),
  223. array('status' => 400)
  224. );
  225. }
  226. }
  227. // Validate active period dates if provided
  228. $active_from = isset($request['active_from']) ? $request['active_from'] : current_time('mysql');
  229. $active_to = isset($request['active_to']) ? $request['active_to'] : date('Y-m-d H:i:s', strtotime('+30 days'));
  230. $validation_result = $this->validate_active_period(array(
  231. 'active_from' => $active_from,
  232. 'active_to' => $active_to
  233. ));
  234. if (is_wp_error($validation_result)) {
  235. return $validation_result;
  236. }
  237. // Check that all chunks are present
  238. if (!$this->file_manager->check_all_chunks($upload_id, $total_chunks)) {
  239. return new WP_Error(
  240. 'qdr_tss_missing_chunks',
  241. __('Not all chunks have been uploaded.', 'qdr-temporary-shared-storage'),
  242. array('status' => 400)
  243. );
  244. }
  245. // Finalize upload
  246. $result = $this->file_manager->finalize_chunked_upload(
  247. $upload_id,
  248. $total_chunks,
  249. $request['original_file_name']
  250. );
  251. if (!$result) {
  252. return new WP_Error(
  253. 'qdr_tss_finalize_failed',
  254. __('Failed to finalize upload.', 'qdr-temporary-shared-storage'),
  255. array('status' => 500)
  256. );
  257. }
  258. $file_path = $result['file_path'];
  259. $file_size = $result['file_size'];
  260. // Generate a unique fileid
  261. $fileid = $this->file_manager->generate_fileid();
  262. // Insert into database
  263. $data = array(
  264. 'fileid' => $fileid,
  265. 'original_file_name' => sanitize_file_name($request['original_file_name']),
  266. 'description' => sanitize_textarea_field($request['description']),
  267. 'message' => isset($request['message']) ? sanitize_textarea_field($request['message']) : '',
  268. 'active_from' => $active_from,
  269. 'active_to' => $active_to,
  270. 'password' => wp_hash_password($request['password']),
  271. 'reference' => isset($request['reference']) ? sanitize_text_field($request['reference']) : '',
  272. 'upload_date' => current_time('mysql'),
  273. 'file_path' => $file_path,
  274. 'file_size' => $file_size
  275. );
  276. $item_id = $this->db_manager->insert_item($data);
  277. if (!$item_id) {
  278. // Delete file if database insert fails
  279. $this->file_manager->delete_file($file_path);
  280. return new WP_Error(
  281. 'qdr_tss_db_failed',
  282. __('Failed to save file information.', 'qdr-temporary-shared-storage'),
  283. array('status' => 500)
  284. );
  285. }
  286. $download_url = site_url('shared-file-download/' . $fileid);
  287. $shortcode = '[qdr_tss_download id="' . $fileid . '"]';
  288. return new WP_REST_Response(array(
  289. 'fileid' => $fileid,
  290. 'permalink' => $download_url,
  291. 'shortcode' => $shortcode
  292. ), 201);
  293. }
  294. /**
  295. * Validate active period dates.
  296. *
  297. * @since 1.0.0
  298. * @param array $data The data array containing active_from and active_to
  299. * @return true|WP_Error True if valid, WP_Error if invalid
  300. */
  301. private function validate_active_period($data) {
  302. // If both dates are provided, validate them
  303. if (isset($data['active_from']) && isset($data['active_to'])) {
  304. $active_from = $data['active_from'];
  305. $active_to = $data['active_to'];
  306. // Skip validation if either field is empty
  307. if (empty($active_from) || empty($active_to)) {
  308. return true;
  309. }
  310. // Parse dates
  311. $from_timestamp = strtotime($active_from);
  312. $to_timestamp = strtotime($active_to);
  313. // Check if dates are valid
  314. if ($from_timestamp === false) {
  315. return new WP_Error(
  316. 'invalid_active_from',
  317. __('Invalid Active From date format.', 'qdr-temporary-shared-storage'),
  318. array('status' => 400)
  319. );
  320. }
  321. if ($to_timestamp === false) {
  322. return new WP_Error(
  323. 'invalid_active_to',
  324. __('Invalid Active To date format.', 'qdr-temporary-shared-storage'),
  325. array('status' => 400)
  326. );
  327. }
  328. // Check if active_from is greater than or equal to active_to
  329. if ($from_timestamp >= $to_timestamp) {
  330. return new WP_Error(
  331. 'invalid_active_period',
  332. __('Active From date must be before Active To date.', 'qdr-temporary-shared-storage'),
  333. array('status' => 400)
  334. );
  335. }
  336. }
  337. return true;
  338. }
  339. }