CustomEmoji.php 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. <?php
  2. namespace App\Models;
  3. use Illuminate\Database\Eloquent\Factories\HasFactory;
  4. use Illuminate\Database\Eloquent\Model;
  5. use Illuminate\Support\Facades\Cache;
  6. use Illuminate\Support\Str;
  7. class CustomEmoji extends Model
  8. {
  9. use HasFactory;
  10. const SCAN_RE = "/(?<=[^[:alnum:]:]|\n|^):([a-zA-Z0-9_]{2,}):(?=[^[:alnum:]:]|$)/x";
  11. const CACHE_KEY = "pf:custom_emoji:";
  12. public static function scan($text, $activitypub = false)
  13. {
  14. if(config('federation.custom_emoji.enabled') == false) {
  15. return [];
  16. }
  17. return Str::of($text)
  18. ->matchAll(self::SCAN_RE)
  19. ->map(function($match) use($activitypub) {
  20. $tag = Cache::remember(self::CACHE_KEY . $match, 14400, function() use($match) {
  21. return self::orderBy('id')->whereDisabled(false)->whereShortcode(':' . $match . ':')->first();
  22. });
  23. if($tag) {
  24. $url = url('/storage/' . $tag->media_path);
  25. if($activitypub == true) {
  26. $mediaType = Str::endsWith($url, '.png') ? 'image/png' : 'image/jpg';
  27. return [
  28. 'id' => url('emojis/' . $tag->id),
  29. 'type' => 'Emoji',
  30. 'name' => $tag->shortcode,
  31. 'updated' => $tag->updated_at->toAtomString(),
  32. 'icon' => [
  33. 'type' => 'Image',
  34. 'mediaType' => $mediaType,
  35. 'url' => $url
  36. ]
  37. ];
  38. } else {
  39. return [
  40. 'shortcode' => $match,
  41. 'url' => $url,
  42. 'static_path' => $url,
  43. 'visible_in_picker' => $tag->disabled == false
  44. ];
  45. }
  46. }
  47. })
  48. ->filter(function($tag) use($activitypub) {
  49. if($activitypub == true) {
  50. return $tag && isset($tag['icon']);
  51. } else {
  52. return $tag && isset($tag['static_path']);
  53. }
  54. })
  55. ->values()
  56. ->toArray();
  57. }
  58. }