Total Complexity | 122 |
Total Lines | 643 |
Duplicated Lines | 0 % |
Changes | 2 | ||
Bugs | 0 | Features | 0 |
Complex classes like MediaRequestHandler often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.
Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.
While breaking up the class, it is a good idea to analyze how other classes use MediaRequestHandler, and based on these observations, apply Extract Interface, too.
1 | <?php |
||
20 | class MediaRequestHandler extends RecordsRequestHandler |
||
21 | { |
||
22 | // RecordRequestHandler configuration |
||
23 | public static $recordClass = Media::class; |
||
24 | public $accountLevelRead = false; |
||
25 | public $accountLevelBrowse = 'User'; |
||
26 | public $accountLevelWrite = 'User'; |
||
27 | public $accountLevelAPI = false; |
||
28 | public $browseLimit = 100; |
||
29 | public $browseOrder = ['ID' => 'DESC']; |
||
30 | |||
31 | // MediaRequestHandler configuration |
||
32 | public $defaultPage = 'browse'; |
||
33 | public $defaultThumbnailWidth = 100; |
||
34 | public $defaultThumbnailHeight = 100; |
||
35 | public $uploadFileFieldName = 'mediaFile'; |
||
36 | public $responseMode = 'html'; |
||
37 | |||
38 | public static $inputStream = 'php://input'; // this is a setting so that unit tests can provide a fake stream :) |
||
39 | |||
40 | public $searchConditions = [ |
||
41 | 'Caption' => [ |
||
42 | 'qualifiers' => ['any','caption'] |
||
43 | ,'points' => 2 |
||
44 | ,'sql' => 'Caption LIKE "%%%s%%"', |
||
45 | ] |
||
46 | ,'CaptionLike' => [ |
||
47 | 'qualifiers' => ['caption-like'] |
||
48 | ,'points' => 2 |
||
49 | ,'sql' => 'Caption LIKE "%s"', |
||
50 | ] |
||
51 | ,'CaptionNot' => [ |
||
52 | 'qualifiers' => ['caption-not'] |
||
53 | ,'points' => 2 |
||
54 | ,'sql' => 'Caption NOT LIKE "%%%s%%"', |
||
55 | ] |
||
56 | ,'CaptionNotLike' => [ |
||
57 | 'qualifiers' => ['caption-not-like'] |
||
58 | ,'points' => 2 |
||
59 | ,'sql' => 'Caption NOT LIKE "%s"', |
||
60 | ], |
||
61 | ]; |
||
62 | |||
63 | public function handle(ServerRequestInterface $request): ResponseInterface |
||
136 | } |
||
137 | } |
||
138 | } |
||
139 | } |
||
140 | |||
141 | |||
142 | public function handleUploadRequest($options = []): ResponseInterface |
||
232 | ]); |
||
233 | } |
||
234 | |||
235 | |||
236 | public function handleMediaRequest($mediaID): ResponseInterface |
||
237 | { |
||
238 | if (empty($mediaID) || !is_numeric($mediaID)) { |
||
239 | return $this->throwNotFoundError('Media ID #%u was not found', $mediaID); |
||
240 | } |
||
241 | |||
242 | // get media |
||
243 | try { |
||
244 | $Media = Media::getById($mediaID); |
||
245 | } catch (Exception $e) { |
||
246 | return $this->throwUnauthorizedError(); |
||
247 | } |
||
248 | |||
249 | if (!$Media) { |
||
250 | return $this->throwNotFoundError('Media ID #%u was not found', $mediaID); |
||
251 | } |
||
252 | |||
253 | if (!$this->checkReadAccess($Media)) { |
||
254 | return $this->throwNotFoundError(); |
||
255 | } |
||
256 | |||
257 | if (isset($_SERVER['HTTP_ACCEPT'])) { |
||
258 | if ($_SERVER['HTTP_ACCEPT'] == 'application/json') { |
||
259 | $this->responseBuilder = JsonBuilder::class; |
||
260 | } |
||
261 | } |
||
262 | |||
263 | if ($this->responseBuilder == JsonBuilder::class) { |
||
264 | return $this->respond('media', [ |
||
265 | 'success' => true |
||
266 | ,'data' => $Media, |
||
267 | ]); |
||
268 | } else { |
||
269 | |||
270 | // determine variant |
||
271 | if ($variant = $this->shiftPath()) { |
||
272 | if (!$Media->isVariantAvailable($variant)) { |
||
273 | return $this->throwNotFoundError(); |
||
274 | } |
||
275 | } else { |
||
276 | $variant = 'original'; |
||
277 | } |
||
278 | |||
279 | // send caching headers |
||
280 | $expires = 60*60*24*365; |
||
281 | if (!headers_sent()) { |
||
282 | // @codeCoverageIgnoreStart |
||
283 | header("Cache-Control: public, max-age=$expires"); |
||
284 | header('Expires: '.gmdate('D, d M Y H:i:s \G\M\T', time()+$expires)); |
||
285 | header('Pragma: public'); |
||
286 | // @codeCoverageIgnoreEnd |
||
287 | } |
||
288 | |||
289 | // media are immutable for a given URL, so no need to actually check anything if the browser wants to revalidate its cache |
||
290 | if (!empty($_SERVER['HTTP_IF_NONE_MATCH']) || !empty($_SERVER['HTTP_IF_MODIFIED_SINCE'])) { |
||
291 | // @codeCoverageIgnoreStart |
||
292 | header('HTTP/1.0 304 Not Modified'); |
||
293 | exit(); |
||
294 | // @codeCoverageIgnoreEnd |
||
295 | } |
||
296 | |||
297 | // initialize response |
||
298 | set_time_limit(0); |
||
299 | $filePath = $Media->getFilesystemPath($variant); |
||
300 | $fp = fopen($filePath, 'rb'); |
||
301 | $size = filesize($filePath); |
||
302 | $length = $size; |
||
303 | $start = 0; |
||
304 | $end = $size - 1; |
||
305 | |||
306 | if (!headers_sent()) { |
||
307 | // @codeCoverageIgnoreStart |
||
308 | header('Content-Type: '.$Media->getMIMEType($variant)); |
||
309 | header('ETag: media-'.$Media->ID.'-'.$variant); |
||
310 | header('Accept-Ranges: bytes'); |
||
311 | // @codeCoverageIgnoreEnd |
||
312 | } |
||
313 | |||
314 | // interpret range requests |
||
315 | if (!empty($_SERVER['HTTP_RANGE'])) { |
||
316 | $chunkStart = $start; |
||
317 | $chunkEnd = $end; |
||
318 | |||
319 | list(, $range) = explode('=', $_SERVER['HTTP_RANGE'], 2); |
||
320 | |||
321 | if (strpos($range, ',') !== false) { |
||
322 | // @codeCoverageIgnoreStart |
||
323 | header('HTTP/1.1 416 Requested Range Not Satisfiable'); |
||
324 | header("Content-Range: bytes $start-$end/$size"); |
||
325 | exit(); |
||
326 | // @codeCoverageIgnoreEnd |
||
327 | } |
||
328 | |||
329 | if ($range == '-') { |
||
330 | $chunkStart = $size - substr($range, 1); |
||
331 | } else { |
||
332 | $range = explode('-', $range); |
||
333 | $chunkStart = $range[0]; |
||
334 | $chunkEnd = (isset($range[1]) && is_numeric($range[1])) ? $range[1] : $size; |
||
335 | } |
||
336 | |||
337 | $chunkEnd = ($chunkEnd > $end) ? $end : $chunkEnd; |
||
338 | if ($chunkStart > $chunkEnd || $chunkStart > $size - 1 || $chunkEnd >= $size) { |
||
339 | // @codeCoverageIgnoreStart |
||
340 | header('HTTP/1.1 416 Requested Range Not Satisfiable'); |
||
341 | header("Content-Range: bytes $start-$end/$size"); |
||
342 | exit(); |
||
343 | // @codeCoverageIgnoreEnd |
||
344 | } |
||
345 | |||
346 | $start = $chunkStart; |
||
347 | $end = $chunkEnd; |
||
348 | $length = $end - $start + 1; |
||
349 | |||
350 | fseek($fp, $start); |
||
351 | // @codeCoverageIgnoreStart |
||
352 | header('HTTP/1.1 206 Partial Content'); |
||
353 | // @codeCoverageIgnoreEnd |
||
354 | } |
||
355 | |||
356 | // finish response |
||
357 | if (!headers_sent()) { |
||
358 | // @codeCoverageIgnoreStart |
||
359 | header("Content-Range: bytes $start-$end/$size"); |
||
360 | header("Content-Length: $length"); |
||
361 | // @codeCoverageIgnoreEnd |
||
362 | } |
||
363 | |||
364 | $buffer = 1024 * 8; |
||
365 | while (!feof($fp) && ($p = ftell($fp)) <= $end) { |
||
366 | if ($p + $buffer > $end) { |
||
367 | $buffer = $end - $p + 1; |
||
368 | } |
||
369 | |||
370 | echo fread($fp, $buffer); |
||
371 | flush(); |
||
372 | } |
||
373 | |||
374 | fclose($fp); |
||
375 | if ($this->responseBuilder != JsonBuilder::class) { |
||
376 | exit; |
||
377 | } |
||
378 | } |
||
379 | } |
||
380 | |||
381 | public function handleInfoRequest($mediaID): ResponseInterface |
||
403 | } |
||
404 | |||
405 | public function handleDownloadRequest($media_id, $filename = false): ResponseInterface |
||
406 | { |
||
407 | if (empty($media_id) || !is_numeric($media_id)) { |
||
408 | $this->throwNotFoundError(); |
||
409 | } |
||
410 | |||
411 | // get media |
||
412 | try { |
||
413 | $Media = Media::getById($media_id); |
||
414 | } catch (Exception $e) { |
||
415 | return $this->throwUnauthorizedError(); |
||
416 | } |
||
417 | |||
418 | |||
419 | if (!$Media) { |
||
420 | return $this->throwNotFoundError(); |
||
421 | } |
||
422 | |||
423 | if (!$this->checkReadAccess($Media)) { |
||
424 | return $this->throwUnauthorizedError(); |
||
425 | } |
||
426 | |||
427 | // determine filename |
||
428 | if (empty($filename)) { |
||
429 | $filename = $Media->Caption ? $Media->Caption : sprintf('%s_%u', $Media->ContextClass, $Media->ContextID); |
||
430 | } |
||
431 | |||
432 | if (strpos($filename, '.') === false) { |
||
433 | // add extension |
||
434 | $filename .= '.'.$Media->Extension; |
||
435 | } |
||
436 | |||
437 | if (!headers_sent()) { |
||
438 | // @codeCoverageIgnoreStart |
||
439 | header('Content-Type: '.$Media->MIMEType); |
||
440 | header('Content-Disposition: attachment; filename="'.str_replace('"', '', $filename).'"'); |
||
441 | header('Content-Length: '.filesize($Media->FilesystemPath)); |
||
442 | // @codeCoverageIgnoreEnd |
||
443 | } |
||
444 | |||
445 | readfile($Media->FilesystemPath); |
||
446 | exit(); |
||
447 | } |
||
448 | |||
449 | public function handleCaptionRequest($media_id): ResponseInterface |
||
482 | ]); |
||
483 | } |
||
484 | |||
485 | public function handleDeleteRequest(ActiveRecord $Record): ResponseInterface |
||
486 | { |
||
487 | // require authentication |
||
488 | $GLOBALS['Session']->requireAccountLevel('Staff'); |
||
489 | |||
490 | if ($mediaID = $this->peekPath()) { |
||
491 | $mediaIDs = [$mediaID]; |
||
492 | } elseif (!empty($_REQUEST['mediaID'])) { |
||
493 | $mediaIDs = [$_REQUEST['mediaID']]; |
||
494 | } elseif (is_array($_REQUEST['media'])) { |
||
495 | $mediaIDs = $_REQUEST['media']; |
||
496 | } |
||
497 | |||
498 | $deleted = []; |
||
499 | foreach ($mediaIDs as $mediaID) { |
||
500 | if (!is_numeric($mediaID)) { |
||
501 | continue; |
||
502 | } |
||
503 | |||
504 | // get media |
||
505 | $Media = Media::getByID($mediaID); |
||
506 | |||
507 | if (!$Media) { |
||
508 | return $this->throwNotFoundError(); |
||
509 | } |
||
510 | |||
511 | if ($Media->destroy()) { |
||
512 | $deleted[] = $Media; |
||
513 | } |
||
514 | } |
||
515 | |||
516 | return $this->respond('mediaDeleted', [ |
||
517 | 'success' => true |
||
518 | ,'data' => $deleted, |
||
519 | ]); |
||
520 | } |
||
521 | |||
522 | public function handleThumbnailRequest(Media $Media = null): ResponseInterface |
||
523 | { |
||
524 | // send caching headers |
||
525 | if (!headers_sent()) { |
||
526 | // @codeCoverageIgnoreStart |
||
527 | $expires = 60*60*24*365; |
||
528 | header("Cache-Control: public, max-age=$expires"); |
||
529 | header('Expires: '.gmdate('D, d M Y H:i:s \G\M\T', time()+$expires)); |
||
530 | header('Pragma: public'); |
||
531 | // @codeCoverageIgnoreEnd |
||
532 | } |
||
533 | |||
534 | // thumbnails are immutable for a given URL, so no need to actually check anything if the browser wants to revalidate its cache |
||
535 | if (!empty($_SERVER['HTTP_IF_NONE_MATCH']) || !empty($_SERVER['HTTP_IF_MODIFIED_SINCE'])) { |
||
536 | header('HTTP/1.0 304 Not Modified'); |
||
537 | exit(); |
||
538 | } |
||
539 | |||
540 | // get media |
||
541 | if (!$Media) { |
||
542 | if (!$mediaID = $this->shiftPath()) { |
||
543 | return $this->throwNotFoundError(); |
||
544 | } elseif (!$Media = Media::getByID($mediaID)) { |
||
545 | return $this->throwNotFoundError(); |
||
546 | } |
||
547 | } |
||
548 | |||
549 | // get format |
||
550 | if (preg_match('/^(\d+)x(\d+)(x([0-9A-F]{6})?)?$/i', $this->peekPath(), $matches)) { |
||
551 | $this->shiftPath(); |
||
552 | $maxWidth = $matches[1]; |
||
553 | $maxHeight = $matches[2]; |
||
554 | $fillColor = !empty($matches[4]) ? $matches[4] : false; |
||
555 | } else { |
||
556 | $maxWidth = $this->defaultThumbnailWidth; |
||
557 | $maxHeight = $this->defaultThumbnailHeight; |
||
558 | $fillColor = false; |
||
559 | } |
||
560 | |||
561 | if ($this->peekPath() == 'cropped') { |
||
562 | $this->shiftPath(); |
||
563 | $cropped = true; |
||
564 | } else { |
||
565 | $cropped = false; |
||
566 | } |
||
567 | |||
568 | // get thumbnail media |
||
569 | try { |
||
570 | $thumbPath = $Media->getThumbnail($maxWidth, $maxHeight, $fillColor, $cropped); |
||
571 | } catch (Exception $e) { |
||
572 | return $this->throwNotFoundError(); |
||
573 | } |
||
574 | |||
575 | // emit |
||
576 | if (!headers_sent()) { |
||
577 | // @codeCoverageIgnoreStart |
||
578 | header("ETag: media-$Media->ID-$maxWidth-$maxHeight-$fillColor-$cropped"); |
||
579 | header("Content-Type: $Media->ThumbnailMIMEType"); |
||
580 | header('Content-Length: '.filesize($thumbPath)); |
||
581 | readfile($thumbPath); |
||
582 | // @codeCoverageIgnoreEnd |
||
583 | } |
||
584 | exit(); |
||
585 | } |
||
586 | |||
587 | |||
588 | public function handleBrowseRequest($options = [], $conditions = [], $responseID = null, $responseData = []): ResponseInterface |
||
611 | } |
||
612 | |||
613 | |||
614 | |||
615 | public function handleMediaDeleteRequest(): ResponseInterface |
||
616 | { |
||
617 | // sanity check |
||
618 | if (empty($_REQUEST['media']) || !is_array($_REQUEST['media'])) { |
||
619 | return $this->throwNotFoundError(); |
||
620 | } |
||
621 | |||
622 | // retrieve photos |
||
623 | $media_array = []; |
||
624 | foreach ($_REQUEST['media'] as $media_id) { |
||
625 | if (!is_numeric($media_id)) { |
||
626 | return $this->throwNotFoundError(); |
||
627 | } |
||
628 | |||
629 | if ($Media = Media::getById($media_id)) { |
||
630 | $media_array[$Media->ID] = $Media; |
||
631 | |||
632 | if (!$this->checkWriteAccess($Media)) { |
||
633 | return $this->throwUnauthorizedError(); |
||
634 | } |
||
635 | } |
||
636 | } |
||
637 | |||
638 | // delete |
||
639 | $deleted = []; |
||
640 | foreach ($media_array as $media_id => $Media) { |
||
641 | if ($Media->delete()) { |
||
642 | $deleted[] = $media_id; |
||
643 | } |
||
644 | } |
||
645 | |||
646 | return $this->respond('mediaDeleted', [ |
||
647 | 'success' => true |
||
648 | ,'deleted' => $deleted, |
||
649 | ]); |
||
650 | } |
||
651 | |||
652 | public function checkUploadAccess() |
||
655 | } |
||
656 | |||
657 | public function throwUploadError($error): ResponseInterface |
||
658 | { |
||
667 |