CustomEmoji.php 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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. protected $guarded = [];
  13. public static function scan($text, $activitypub = false)
  14. {
  15. if((bool) config_cache('federation.custom_emoji.enabled') == false) {
  16. return [];
  17. }
  18. return Str::of($text)
  19. ->matchAll(self::SCAN_RE)
  20. ->map(function($match) use($activitypub) {
  21. $tag = Cache::remember(self::CACHE_KEY . $match, 14400, function() use($match) {
  22. return self::orderBy('id')->whereDisabled(false)->whereShortcode(':' . $match . ':')->first();
  23. });
  24. if($tag) {
  25. $url = url('/storage/' . $tag->media_path);
  26. if($activitypub == true) {
  27. $mediaType = Str::endsWith($url, '.png') ? 'image/png' : 'image/jpg';
  28. return [
  29. 'id' => url('emojis/' . $tag->id),
  30. 'type' => 'Emoji',
  31. 'name' => $tag->shortcode,
  32. 'updated' => $tag->updated_at->toAtomString(),
  33. 'icon' => [
  34. 'type' => 'Image',
  35. 'mediaType' => $mediaType,
  36. 'url' => $url
  37. ]
  38. ];
  39. } else {
  40. return [
  41. 'shortcode' => $match,
  42. 'url' => $url,
  43. 'static_url' => $url,
  44. 'visible_in_picker' => $tag->disabled == false
  45. ];
  46. }
  47. }
  48. })
  49. ->filter(function($tag) use($activitypub) {
  50. if($activitypub == true) {
  51. return $tag && isset($tag['icon']);
  52. } else {
  53. return $tag && isset($tag['static_url']);
  54. }
  55. })
  56. ->values()
  57. ->toArray();
  58. }
  59. }