Link.php 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. <?php
  2. // {{{ License
  3. // This file is part of GNU social - https://www.gnu.org/software/social
  4. //
  5. // GNU social is free software: you can redistribute it and/or modify
  6. // it under the terms of the GNU Affero General Public License as published by
  7. // the Free Software Foundation, either version 3 of the License, or
  8. // (at your option) any later version.
  9. //
  10. // GNU social is distributed in the hope that it will be useful,
  11. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. // GNU Affero General Public License for more details.
  14. //
  15. // You should have received a copy of the GNU Affero General Public License
  16. // along with GNU social. If not, see <http://www.gnu.org/licenses/>.
  17. // }}}
  18. namespace Component\Link;
  19. use App\Core\DB\DB;
  20. use App\Core\Modules\Component;
  21. use App\Entity;
  22. use App\Entity\NoteToLink;
  23. use App\Util\Common;
  24. use InvalidArgumentException;
  25. class Link extends Component
  26. {
  27. /**
  28. * "Perfect URL Regex", courtesy of https://urlregex.com/
  29. */
  30. const URL_REGEX = <<<END
  31. %(?:(?:https?|ftp)://)(?:\\S+(?::\\S*)?@|\\d{1,3}(?:\\.\\d{1,3}){3}|(?:(?:[a-z\\d\\x{00a1}-\\x{ffff}]+-?)*[a-z\\d\\x{00a1}-\\x{ffff}]+)(?:\\.(?:[a-z\\d\\x{00a1}-\\x{ffff}]+-?)*[a-z\\d\\x{00a1}-\\x{ffff}]+)*(?:\\.[a-z\\x{00a1}-\\x{ffff}]{2,6}))(?::\\d+)?(?:[^\\s]*)?%iu
  32. END;
  33. /**
  34. * TODO PLACEHOLDER
  35. */
  36. public function onProcessNoteContent(int $note_id, string $content)
  37. {
  38. if (Common::config('attachments', 'process_links')) {
  39. $matched_urls = [];
  40. $processed_urls = false;
  41. preg_match_all(self::URL_REGEX, $content, $matched_urls, PREG_SET_ORDER);
  42. foreach ($matched_urls as $match) {
  43. try {
  44. $link_id = Entity\Link::getOrCreate($match[0])->getId();
  45. DB::persist(NoteToLink::create(['link_id' => $link_id, 'note_id' => $note_id]));
  46. $processed_urls = true;
  47. } catch (InvalidArgumentException) {
  48. continue;
  49. }
  50. }
  51. if ($processed_urls) {
  52. DB::flush();
  53. }
  54. }
  55. }
  56. }