TXT.php 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. <?php
  2. /**
  3. * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
  4. * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
  5. * SPDX-License-Identifier: AGPL-3.0-only
  6. */
  7. namespace OC\Preview;
  8. use OCP\Files\File;
  9. use OCP\Files\FileInfo;
  10. use OCP\IImage;
  11. class TXT extends ProviderV2 {
  12. /**
  13. * {@inheritDoc}
  14. */
  15. public function getMimeType(): string {
  16. return '/text\/plain/';
  17. }
  18. /**
  19. * {@inheritDoc}
  20. */
  21. public function isAvailable(FileInfo $file): bool {
  22. return $file->getSize() > 0;
  23. }
  24. /**
  25. * {@inheritDoc}
  26. */
  27. public function getThumbnail(File $file, int $maxX, int $maxY): ?IImage {
  28. if (!$this->isAvailable($file)) {
  29. return null;
  30. }
  31. $content = $file->fopen('r');
  32. if ($content === false) {
  33. return null;
  34. }
  35. $content = stream_get_contents($content, 3000);
  36. //don't create previews of empty text files
  37. if (trim($content) === '') {
  38. return null;
  39. }
  40. $lines = preg_split("/\r\n|\n|\r/", $content);
  41. // Define text size of text file preview
  42. $fontSize = $maxX ? (int)((1 / 32) * $maxX) : 5; //5px
  43. $lineSize = ceil($fontSize * 1.5);
  44. $image = imagecreate($maxX, $maxY);
  45. imagecolorallocate($image, 255, 255, 255);
  46. $textColor = imagecolorallocate($image, 0, 0, 0);
  47. $fontFile = __DIR__;
  48. $fontFile .= '/../../../core';
  49. $fontFile .= '/fonts/NotoSans-Regular.ttf';
  50. $canUseTTF = function_exists('imagettftext');
  51. foreach ($lines as $index => $line) {
  52. $index = $index + 1;
  53. $x = 1;
  54. $y = (int)($index * $lineSize);
  55. if ($canUseTTF === true) {
  56. imagettftext($image, $fontSize, 0, $x, $y, $textColor, $fontFile, $line);
  57. } else {
  58. $y -= $fontSize;
  59. imagestring($image, 1, $x, $y, $line, $textColor);
  60. }
  61. if (($index * $lineSize) >= $maxY) {
  62. break;
  63. }
  64. }
  65. $imageObject = new \OCP\Image();
  66. $imageObject->setResource($image);
  67. return $imageObject->valid() ? $imageObject : null;
  68. }
  69. }